Skip to content

Instantly share code, notes, and snippets.

@thorwhalen
Last active May 20, 2020 19:56
Show Gist options
  • Save thorwhalen/4da0e43d815c8f89839cd7888b61a3fe to your computer and use it in GitHub Desktop.
Save thorwhalen/4da0e43d815c8f89839cd7888b61a3fe to your computer and use it in GitHub Desktop.
Investigate the subtypes of various python callables
"""
Code that prints this table (meant to study the type-differences of different callables):
```
MethodType FunctionType has_self qualname_levels dunders
name
class method True False True 2 27
instance method False True False 2 35
static method False True False 2 35
"instantiated" class method True False True 2 27
"instantiated" instance method True False True 2 27
"instantiated" static method False True False 2 35
"plain" function False True False 1 35
lambda False True False 1 35
```
See [this stackoverflow question](https://stackoverflow.com/questions/61919480/subtypes-of-python-callables-how-to-tell-if-an-object-is-a-class-instance-sta) I posted about it.
"""
def f(): ...
class X:
@classmethod
def c(cls): ...
@staticmethod
def s(): ...
#instance method
def i(self): ...
from types import MethodType, FunctionType
d = {
'class method': X.c,
'instance method': X.i,
'static method': X.s,
'"instantiated" class method': X().c,
'"instantiated" instance method': X().i,
'"instantiated" static method': X().s,
'"plain" function': f,
'lambda': lambda: None
}
t = list()
for name, obj in d.items():
t.append({'name': name,
'MethodType': isinstance(obj, MethodType),
'FunctionType': isinstance(obj, FunctionType),
'has_self': hasattr(obj, '__self__'),
'qualname_levels': len(obj.__qualname__.split('.')),
'dunders': len(dir(obj)),
})
print(pd.DataFrame(t).set_index('name').to_string())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment