Dir () - how can I distinguish between functions / method and simple attributes?

dir()

returns a list of all defined names, but it is annoying to try to call a function I only see in the list, only to discover that it is actually an attribute, or to try to access an attribute, only to find that it is actually revoked ... How can I get dir()

more informative?

+3


source to share


3 answers


To display a list of specific names in a module, such as a math module and their types, you could do:

[(name,type(getattr(math,name))) for name in dir(math)]

      



getattr (math, name) returns an object (function or otherwise) from the math module named by the string value in the "name" variable. For example type (getattr (math, 'pi')) is 'float'

+2


source


It is impossible to make dir

more informative, as you put it, but you can use callable

and getattr

function:

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

      




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

+3


source


Another way is to use the function getmembers

in inspect

. You can get a similar result for James by one of

from inspect import getmembers

getmembers(obj)  # => ...

      

For more information, please take a look at:

https://docs.python.org/2/library/inspect.html#inspect.getmembers

0


source







All Articles