Python - dir() - how can I differentiate between functions/method and simple attributes?

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'


There isn't a way to make dir 'more informative' as you put it, but you can use the callable and getattr functions:

[(a, 'func' if callable(getattr(obj, a)) else 'attr') for a in dir(obj)]

Obviously functions are still attributes themselves, but you get the idea.

Tags:

Python