staticmethod makes my brain hurt
alex23
wuwei23 at gmail.com
Wed Nov 16 21:44:00 EST 2011
On Nov 17, 12:30 pm, Roy Smith <r... at panix.com> wrote:
> class C:
> @staticmethod
> def foo():
> pass
>
> print "inside", foo, callable(foo)
>
> print "outside", C.foo, callable(C.foo)
>
> I don't understand. Why is foo not callable inside of the class
> definition?
Consider this:
>>> def foo(): pass
...
>>> foo = staticmethod(foo)
>>> callable(foo)
False
A staticmethod by itself does not appear to be callable.
Your internal 'foo' is referring to the staticmethod wrapper. Your
external 'C.foo' refers to the result returned by the class
mechanism's __getattr__, which I'm guessing is munged into a callable
at that point.
Where this comes up is that I'm trying to use a callable
> default in mongoengine:
>
> class User(Document):
> @staticmethod
> def _get_next_id():
> [blah, blah, blah]
> return id
>
> user_id = IntField(required=True, default=_get_next_id)
What you're effectively trying to do is use a class before it has been
constructed to help construct itself.
Just define it as a helper function before the class declaration.
More information about the Python-list
mailing list