Python dir() Method

The dir() method in Python is a built-in function that returns a list of names in the current local scope or a list of attributes of an object.




The object parameter is the object you want to see the valid attributes of.


class Child:
  name = "El"
  age = 11
  country = "USA"



['__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', 'country', 'name']

The dir() tries to return the list of valid attributes of an object.

  1. If an object has the __dir__() method, the method will be called and must return the list of attributes.
  2. If an object doesn’t t have the __dir__() method, this method tries to find information from the __dict__ attribute (if defined), the d from the type object. In this case, a list returned from dir() may not be complete.

If the object is not passed to the dir() method, it returns the list of names in the current local scope.

Example 2



['__annotations__', '__builtins__', '__cached__', 
'__doc__', '__file__', '__loader__', '__name__', 
'__package__', '__spec__']

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.