Menu Close

Python dir Function

python dir function

In this tutorial, we are going to learn all about the Python dir() function to get all the properties and methods of an object. Python dir function is the best python built-in function when you want to access all the methods and properties of any object.

In the previous python built-in functions tutorial, we have seen the Python dict function to create the dictionary.

Python dir Function

Python dir function is a Python built-in function which means you don’t need to install it by using the pip command, dir() function is used to return all the properties and methods of the object. This can be called without any argument or parameter but in that case, it will return all the names in the current scope.

This function will return all the properties and methods even all the built-in properties which are the default for all the objects.

Syntax

The syntax of dir() function in Python is:-

dir(object)

Parameter

dir function in python accepts one optional parameter that is called object:-

  • object:- Optional, The object you want to see the valid attributes of.

Return Value

The return type of the dir() function in Python depend on the following scenario. You have to remember one thing, dir() function always returns list of strings.

  • In the case of a module, It will return a list of all the module’s attributes.
  • For Class, It will return a list of names of all the valid attributes and base attributes as well.
  • If no parameter is passing, it will return a list of the attributes of the current scope.

Python dir function examples

Here I will take various examples of pytheon dir function so that, you don’t have any confusion regarding the Python dir() function in the future.

Example: Returning Attributes of Class


class Person:
	age = 21
	name = 'John'
	city = 'California'
	
	def printNow(self):
		print(self.name +  ' ' + self.city)


#Create instance of Person class
p1 = Person()

#access printNow() method using p1 object.
p1.printNow()

#access all the properties and methods of the p1 object.
print(dir(Person))

Output

John California
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'city', 'name', 'printNow']

Example: Returning Attributes of Module

In this example, I am returning all the attributes of the DateTime module which is a popular python built-in module.


# importing datetime module
import datetime

print("Properties and methods of datetime module are:- ")
# use dir() function to return all the properties and method datetime  of datetime module
print(dir(datetime))

Output

['MAXYEAR', 'MINYEAR', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time', 'timedelta', 'timezone', 'tzinfo']

Example: Using dir() function without argument

In the case without arguments or parameters, it will return all the names in the current name scope.


# calling dir() function without importing module
print("Names without importing module:- ")
print(dir())


print("----------------------------")
# importing datetime module
import datetime

print("Attributes after importing module:- ")
print(dir())

Output

Names without importing module:- 
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
----------------------------
Attributes after importing module:- 
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'datetime']

As you can see in the above output, module datetime was successfully added to local namespaces.

👉 Python DateTime module tutorial

List object properties and methods

To access all the properties and methods of the list object, you can use the python dir() function.

Example:


x = dir(dict)
print(x)

Output

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Dictionary object properties and methods

To access all the properties and methods of the dictionary object, you can use the dir() function.

Example:

print(dir(dict))

Output

['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

User define dir() method

If a class contains the dir() magic method, In that case, dir() method will return the attributes that it contains otherwise it will return all the attributes of the class.

Example:- User defined __dir__ method


class Person:

    def __init__(self, fname, lname):
        self.first_name = fname
        self.last_name = lname

    def __dir__(self):
        return [self.first_name, self.last_name]


# creating object of class
p1 = Person("Vishvajit", "Rao")

# return attributes of the class Person
print("Attributes of Person class:- ")
print(dir(p1))

Output

Attributes of Person class:- 
['Rao', 'Vishvajit']

Conclusion

In this tutorial, you have seen all about the python dir() function to get all the properties and methods of any object. Using the Python dir method, you can find all the properties and methods of your own objects. You can use the dir() function to get a list of attributes of the class, modules, objects, and local scopes.

If this article helped you, please keep visiting for further python built-in functions tutorials.

Other Python built-in functions


For more information:- Click Here

Thanks for your valuable time… 🙏🙏❤️❤️

Python filter() Function
Python iter() Function

Related Posts