Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 727
tadasajon Avatar asked Nov 08 '14 14:11

tadasajon


People also ask

What does dir () mean in python?

The dir() function returns all properties and methods of the specified object, without the values. This function will return all the properties and methods, even built-in properties which are default for all object.

How can I find the methods or attributes of an object in python?

Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.

What is the use of help () and dir () functions in python?

help() – it is built in function python which when executed, returns docstring along with module name, filename, function name and constant of the module passed as argument. dir()- it is built in function in python which is used to display properties and methods of object passed as an argument in it.

What does the python dir () function show when we pass an object into it as a parameter?

dir() function in Python. dir() is a powerful inbuilt function in Python3, which returns list of the attributes and methods of any object (say functions , modules, strings, lists, dictionaries etc.) Returns : dir() tries to return a valid list of attributes of the object it is called upon.


1 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'

like image 79
James K Avatar answered Sep 20 '22 18:09

James K