That's because dir()
returns a list of strings:
>>> import string
>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']
String values are not callable; these are not the actual attribute values, they are the names.
If you wanted to to test those names as attributes on the string
module, you'd have to use getattr()
, or use the vars()
function to get the strings
namespace as a dictionary:
>>> getattr(string, 'Formatter')
<class 'string.Formatter'>
>>> callable(getattr(string, 'Formatter'))
True
>>> [name for name in dir(string) if callable(getattr(string, name))]
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', 'capwords']
>>> [name for name, obj in vars(string).items() if callable(obj)]
['capwords', '_ChainMap', '_TemplateMetaclass', 'Template', 'Formatter']
The order differs here because dictionaries are unordered and dir()
always sorts the return value. For modules, dir(module)
simply returns sorted(vars(module))
.
If you wanted the callable objects themselves and not the names, just filter the values of the vars()
dictionary:
[obj for obj in vars(string).values() if callable(obj)]