Calling class staticmethod within the class body?
Solution 1
staticmethod
objects apparently have a __func__
attribute storing the original raw function (makes sense that they had to). So this will work:
class Klass(object):
@staticmethod # use as decorator
def stat_func():
return 42
_ANS = stat_func.__func__() # call the staticmethod
def method(self):
ret = Klass.stat_func()
return ret
As an aside, though I suspected that a staticmethod object had some sort of attribute storing the original function, I had no idea of the specifics. In the spirit of teaching someone to fish rather than giving them a fish, this is what I did to investigate and find that out (a C&P from my Python session):
>>> class Foo(object):
... @staticmethod
... def foo():
... return 3
... global z
... z = foo
>>> z
<staticmethod object at 0x0000000002E40558>
>>> Foo.foo
<function foo at 0x0000000002E3CBA8>
>>> dir(z)
['__class__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> z.__func__
<function foo at 0x0000000002E3CBA8>
Similar sorts of digging in an interactive session (dir
is very helpful) can often solve these sorts of question very quickly.
Solution 2
This is the way I prefer:
class Klass(object):
@staticmethod
def stat_func():
return 42
_ANS = stat_func.__func__()
def method(self):
return self.__class__.stat_func() + self.__class__._ANS
I prefer this solution to Klass.stat_func
, because of the DRY principle.
Reminds me of the reason why there is a new super()
in Python 3 :)
But I agree with the others, usually the best choice is to define a module level function.
For instance with @staticmethod
function, the recursion might not look very good (You would need to break DRY principle by calling Klass.stat_func
inside Klass.stat_func
). That's because you don't have reference to self
inside static method.
With module level function, everything will look OK.
Solution 3
This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.
From the source code:
It can be called either on the class (e.g.
C.f()
) or on an instance (e.g.C().f()
); the instance is ignored except for its class.
But not directly from inside the class while it is being defined.
But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.
Solution 4
What about injecting the class attribute after the class definition?
class Klass(object):
@staticmethod # use as decorator
def stat_func():
return 42
def method(self):
ret = Klass.stat_func()
return ret
Klass._ANS = Klass.stat_func() # inject the class attribute with static method value
Solution 5
What about this solution? It does not rely on knowledge of @staticmethod
decorator implementation. Inner class StaticMethod plays as a container of static initialization functions.
class Klass(object):
class StaticMethod:
@staticmethod # use as decorator
def _stat_func():
return 42
_ANS = StaticMethod._stat_func() # call the staticmethod
def method(self):
ret = self.StaticMethod._stat_func() + Klass._ANS
return ret
Related videos on Youtube
![martineau](https://i.stack.imgur.com/JEycE.png?s=256&g=1)
martineau
Most of my interest and expertise is in software written in Python and C/C++. I've been writing computer code most of my adult life, beginning my senior year in high school working at a part-time NASA job utilizing a CDC 7600 (generally regarded as the fastest supercomputer in the world at the time), punched cards, and FORTRAN IV, soon followed by a mixture of Applesoft BASIC and 6502 assembler on a 64K Apple II personal computer purchased while attending college in California. I currently live in the state of Washington in the USA, at the base of the western foothills of the Cascade mountains, near a small town named Enumclaw, which lies south of Seattle and east of Tacoma. NOTE: Please don't contact me via LinkedIn to ask to be added to my network.
Updated on September 01, 2021Comments
-
martineau almost 3 years
When I attempt to use a static method from within the body of the class, and define the static method using the built-in
staticmethod
function as a decorator, like this:class Klass(object): @staticmethod # use as decorator def _stat_func(): return 42 _ANS = _stat_func() # call the staticmethod def method(self): ret = Klass._stat_func() + Klass._ANS return ret
I get the following error:
Traceback (most recent call last): File "call_staticmethod.py", line 1, in <module> class Klass(object): File "call_staticmethod.py", line 7, in Klass _ANS = _stat_func() TypeError: 'staticmethod' object is not callable
I understand why this is happening (descriptor binding), and can work around it by manually converting
_stat_func()
into a staticmethod after its last use, like so:class Klass(object): def _stat_func(): return 42 _ANS = _stat_func() # use the non-staticmethod version _stat_func = staticmethod(_stat_func) # convert function to a static method def method(self): ret = Klass._stat_func() + Klass._ANS return ret
So my question is:
Are there cleaner or more "Pythonic" ways to accomplish this?
-
Benjamin Hodgson over 11 yearsIf you're asking about Pythonicity, then the standard advice is not to use
staticmethod
at all. They are usually more useful as module-level functions, in which case your problem is not an issue.classmethod
, on the other hand... -
martineau over 11 years@poorsod: Yes, I'm aware of that alternative. However in the actual code where I encountered this issue, making the function a static method rather than putting it at module-level makes more sense than it does in the simple example used in my question.
-
-
martineau over 11 yearsThis is similar to my first attempts at a work around, but I would prefer something that was inside the class...partially because the attribute involved has a leading underscore and is private.
-
martineau over 11 yearsGood update...I was just about to ask how you knew this since I don't see it in the documentation -- which makes me a little nervous about using it because it might be an "implementation detail".
-
martineau over 11 yearsAs I said in my question, I understand why the original code didn't work. Can you explain (or provide a link to something that does) why it's considered unPythonic?
-
Keith over 11 yearsThe staticmethod requires the class object itself to work correctly. But if you call it from within the class at the class level the class isn't really fully defined at that point. So you can't reference it yet. It's ok to call the staticmethod from outside the class, after it's defined. But "Pythonic" is not actually well defined, much like aesthetics. I can tell you my own first impression of that code was not favorable.
-
martineau over 11 yearsAfter further reading I see that
__func__
is just another name forim_func
and was added to Py 2.6 for Python 3 forwards-compatibility. -
martineau over 11 yearsImpression of which version (or both)? And why, specifically?
-
Ben over 11 years@martineau Not in this context. Bound and unbound method objects have an
im_func
attribute for getting the raw function, and the__func__
attribute of these method objects is the same asim_func
.staticmethod
objects do not have anim_func
attribute (as shown by mydir
posting above, and confirmed in an actual interpreter session). -
martineau over 11 yearsI see, so technically it is undocumented in this context.
-
Keith over 11 yearsI can only guess at what your ultimate goal is, but it seems to me that you want a dynamic, class-level attribute. This looks like a job for metaclasses. But yet again there might be a simpler way, or another way to look at the design that eliminates and simplifies without sacrificing the functionality.
-
martineau over 11 yearsNo, what I want to do is actually pretty simple -- which is to factor out some common code and reuse it, both to create a private class attribute at class-creation time, and later on within one or more class methods. This common code has no use outside the class, so I naturally want it to be a part of it. Using a metaclass (or a class decorator) would work, but that seems like overkill for something that ought to be easy to do, IMHO.
-
Keith over 11 yearsYou can create a class attribute at class creation time with this:
_ANS = 42
in the class scope. That is the most common method. -
martineau over 11 yearsThat's fine for class attributes which are trivial constants as in my simplified example code, but not so much if they're not and require some computation.
-
martineau about 11 yearsI'm going to accept your answer now because it still works in Python 2.7.4 and 3.3, so I'm less worried about it being undocumented. Thanks!
-
martineau about 10 years+1 for creativity, but I'm no longer worried about using
__func__
because it is now officially documented (see section Other Language Changes of the What's New in Python 2.7 and its reference to Issue 5982). Your solution is even more portable, since it would probably also work in Python versions before to 2.6 (when__func__
was first introduced as a synonym ofim_func
). -
martineau over 9 yearsWhile I agree that using
self.__class__.stat_func()
in regular methods has advantages (DRY and all that) over usingKlass.stat_func()
, that wasn't really the topic of my question -- in fact I avoided using the former as not to cloud the issue of the inconsistency. -
asmeurer about 7 yearsIt's not really an issue of DRY per se.
self.__class__
is better because if a subclass overridesstat_func
, thenSubclass.method
will call the subclass'sstat_func
. But to be completely honest, in that situation it is much better to just use a real method instead of a static one. -
benselme almost 7 yearsThis is the only solution that works with Python 2.6.
-
Akshay Hazari over 6 yearsHow do we achieve this when there are more arguments to the function. To me it gives TypeError : function takes exactly 1 argument (0 given)
-
Ben over 6 years@AkshayHazari The
__func__
attribute of a static method gets you a reference to the original function, exactly as if you had never used thestaticmethod
decorator. So if your function requires arguments, you'll have to pass them when calling__func__
. The error message you quite sounds like you have not given it any arguments. If thestat_func
in this post's example took two arguments, you would use_ANS = stat_func.__func__(arg1, arg2)
-
Akshay Hazari over 6 years@Ben (arg1,arg2) cannot be variables. We would be making a function call. When you call it like that you have to put in literals. I have a different use case. Kind of miss read the question. Got redirected here from somewhere.
-
Ben over 6 years@AkshayHazari I'm not sure I understand. They can be variables, they just have to be in-scope variables: either defined earlier in the same scope where the class is defined (often global), or defined earlier within the class scope (
stat_func
itself is such a variable). Did you mean you can't use instance attributes of the class you're defining? That's true, but unsurprising; we don't have an instance of the class, since we're still defining the class! But anyway, I just meant them as standins for whatever arguments you wanted to pass; you could use literals there. -
martineau about 6 years@asmeurer: I can't use a real method because no instances of the class have been created yet—they can't be since the class itself hasn't even been completely defined yet.
-
martineau about 6 years@benselme: I can't verify your claim because I don't have Python 2.6 installed, but serious doubt it's the only only one...
-
whitey04 over 5 yearsI wanted a way to call the static method for my class (which is inherited; so the parent actually has the function) and this seems best by far (and will still work if I override it later).
-
martineau about 5 yearsFor anyone reading this far, you can use this link, Pythonic, to see what Keith referred to in his first comment (courtesy of The Wayback Machine).
-
Abhijit Sarkar over 4 yearsDoesn't seem to work, see stackoverflow.com/q/59474374/839733
-
merlachandra about 3 yearsCan I first call Klass._ANS = Klass.stat_func() and then define class? Is this not allowed, I see an error class doesn't exist when I try this?