dir() returns a list of all the defined names, but it is annoying to try to call function I see listed only to discover it is actually an attribute, or to try to access an attribute only to discover it is actually a callable. How can I get dir() to be more informative?
4 Answers
To show a list of the defined names in a module, for example the math module, and their types you could do:
[(name,type(getattr(math,name))) for name in dir(math)]
getattr(math,name) returns the object (function, or otherwise) from the math module, named by the value of the string in the variable "name". For example type(getattr(math,'pi')) is 'float'
Comments
Another way is to use getmembers function in inspect. You can get a similar result to James's one by
from inspect import getmembers
getmembers(obj) # => ...
For more information, please take a look at:
https://docs.python.org/2/library/inspect.html#inspect.getmembers
attrs = [a for a in dir(obj) if not callable(a)]andfuncs = [a for a in dir(obj) if callable(a)]dirgives strings.attrs = [a for a in dir(obj) if not callable(getattr(obj, a))]callable()also finds classes because they are callable.