AppDividend
Latest Code Tutorials

Python dir() Example | dir() Function In Python Tutorial

0

Python dir() Example | dir() Function In Python is today’s topic. Python dir() is the powerful inbuilt function in Python3, which returns a list of the attributes and methods of any object. The dir method tries to return the list of valid attributes of an object.

Python dir()

The dir() function returns all the properties and methods of a specified object, without the values.

Python dir() method will return all the properties and methods, even built-in properties which are the default for all the objects.

The syntax of the dir() function is following.

dir(object)

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

See the following code example.

# app.py

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

print(dir(Child))

See the following output.

➜  pyt python3 app.py
['__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']
➜  pyt

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

  1. If an object has __dir__() method, the method will be called and must return the list of attributes.
  2. If an object doesn’t have __dir__() method, this method tries to find an information from the __dict__ attribute (if defined), and from 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.

See the following code.

# app.py

print(dir())

See the following output.

➜  pyt python3 app.py
['__annotations__', '__builtins__', '__cached__', 
'__doc__', '__file__', '__loader__', '__name__', 
'__package__', '__spec__']
➜  pyt

#dir() function with Python list

Let’s define the Python List and check with the dir() function to get all the functions and properties of the list. We will take a list of numbers.

# app.py

number = [11, 21, 19]
print(dir(number))

See the following output.

➜  pyt python3 app.py
['__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']
➜  pyt

#dir() function with Python tuple and dictionary

Let’s use the dir() function with Python tuple and dictionary.

# app.py

print('See the dictionary')
dictA = {'name': 'Eleven', 'show': 'Stranger Things'}
print(dir(dictA))
print('See the tuple')
tupleA = ('Eleven', 'Alexie', 'Hopper')
print(dir(tupleA))

See the following output.

➜  pyt python3 app.py
See the dictionary
['__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']
See the tuple
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', 
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', 
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', 
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__', 'count', 'index']
➜  pyt

#The dir() on User-defined Object

Okay, now let’s create a User-defined object and then use the dir() function.

# app.py

class Eleven:
  def __dir__(self):
    return ['age', 'name', 'power']
    

supergirl = Eleven()
print(dir(supergirl))

See the following output.

➜  pyt python3 app.py
['age', 'name', 'power']
➜  pyt

#Import other libraries

Okay, let’s import the math library and see the contents of the math library. See the following code.

# app.py

import math
print(dir(math))

See the below output.

➜  pyt python3 app.py
['__doc__', '__file__', '__loader__', '__name__', '__package__', 
'__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 
'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 
'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 
'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 
'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 
'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 
'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
➜  pyt

#Uses of dir() function

  1. Python dir() has its own set of uses. It is usually used for the debugging purposes in the simple day to day programs, and even in large the projects taken up by the team of developers. The capability of the dir() function is to list out all the attributes of that parameter passed, is really useful when handling a lot of classes and functions, separately.
  2. The dir() function can also list out for all the available attributes for the module/list/dictionary. So, it also gives us the information on the operations we can perform with the list or module, which can be useful when having little to no info about that module. It also helps to know the new modules faster.

Finally, Python dir() Example | dir() Function In Python Tutorial is over.

Leave A Reply

Your email address will not be published.

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