13

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
  • 7
    attrs = [a for a in dir(obj) if not callable(a)] and funcs = [a for a in dir(obj) if callable(a)] Commented Nov 8, 2014 at 14:20
  • 2
    @ChinmayKanchi That won't work- dir gives strings. Commented Nov 8, 2014 at 14:59
  • 1
    Sorry, attrs = [a for a in dir(obj) if not callable(getattr(obj, a))] Commented Nov 8, 2014 at 15:19
  • Just FYI, callable() also finds classes because they are callable. Commented Mar 31, 2023 at 16:34

4 Answers 4

11

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'

Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

1

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

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.