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

Question:

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?

Asked By: tadasajon

||

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’

Answered By: James K

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.

Answered By: anon582847382

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

Answered By: gh640

You can see details on this way :

for functions_variables_list in dir( module_name ):
  print(functions_variables_list, type( getattr(module_name, functions_variables_list)))

PS: For default function details see: dir(), type(), getattr()

Answered By: javmah

this is great info, thanks everyone….
bit of a newb so AIA…
so with:
[(name,type(getattr(tuple,name))) for name in dir(tuple)]
I’m confused by seeing a bunch of "wrapper_descriptor" or "method_descriptor" results – firstly, what do these mean (not clear on wrappers but will read up, but moreover if its a method why isn’t it documented/visible?), but secondly, I don’t see many of these in Python references. ie: there is no "reduce" method or function documented for tuples. How can I tell if this function/method is accessible to me, and if so, how it is used?

I presume these functions aren’t documented because they’re either internal-use only to the class or simply not useful…but obviously when I see these I start wondering about what they might be used for….which killed the cat…lol.

thx-

Answered By: S M
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.