Dealing with non-callable classmethod objects
Cameron Simpson
cs at cskk.id.au
Sat Nov 12 15:52:52 EST 2022
On 12Nov2022 18:44, Weatherby,Gerard <gweatherby at uchc.edu> wrote:
>Use the inspect module as Cameron suggested.
My suggestions was not for the post-construction class attributes but
for the comtents of the "_attrs" mapping. Post construction the class
method is callable. But the classmethod object stashed in "_attrs" is
not.
However, it _is_ of type "classmethod", which means it can be identified
without using "inspect". Here's an alternative demo programme:
class Demo:
@classmethod
def us(cls):
print(cls.__name__)
@staticmethod
def double(x):
return x + x
def triple(self, y):
return 3 * y
_attrs = {
"double": double,
"triple": triple,
"us": us,
}
for name, attr in Demo._attrs.items():
print(name, "->", attr, type(attr))
print(" is class method =", type(attr) is classmethod)
print(" is callable =", callable(attr))
if inspect.ismethod(attr):
print(" ismethod")
if inspect.isfunction(attr):
print(" isfunction")
breakpoint()
I stuck a breakpoint in so that I could inspect things after the run.
The run looks like this:
py3 demo1.py
double -> <staticmethod object at 0x10e9c1340> <class 'staticmethod'>
is class method = False
is callable = False
triple -> <function Demo.triple at 0x10eafcd30> <class 'function'>
is class method = False
is callable = True
isfunction
us -> <classmethod object at 0x10e9c1250> <class 'classmethod'>
is class method = True
is callable = False
so just testing "type(attr) is classmethod" identifies the unpromoted
class method.
I need to real Ian's other post to see what he did to turn that into a
callable factory function.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Python-list
mailing list