Python dir()
Srinivas Ramakrishna
Posted on October 19, 2021
ItsMyCode |
The dir()
method is an inbuilt function in Python which returns all the valid list of attributes and methods of any object. ( functions , dict , list , string , tuple etc.)
dir() Syntax
The syntax of the dir()
method is:
**dir([object])**
dir() Parameters
The dir()
method takes only one argument as an object.
- **object(optional) – **The object which you want to see the valid attributes.
dir() Return Value
dir()
method returns the valid list of attributes for a given object.
The dir()
function behaves differently for different types of objects. It aims to return the relevant information rather than complete information.
- For Class Objects – Returns all the names of valid attributes and the base attributes of the class object.
- F or Modules or Library – It tries to return a list of names of all the attributes in that module.
- If no parameter is passed to the
dir()
method, it returns a list of names in the current local scope.
Example 1: How dir() works?
The below example provides all the valid attributes of a list object.
# dir() method for list
lst_numbers = [1, 2, 3, 4, 5]
print(dir(lst_numbers))
Output
[' __add__', ' __class__', ' __class_getitem__', ' __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']
Example 2: When no parameters are passed to dir() method with and without importing external libraries.
If no parameter is passed to the dir()
method, it returns a list of names in the current local scope.
- In the first case, we have not imported any module, and
dir()
methods return the default names. - In the second case, we have imported two modules(random and math), and the
dir()
method returns these module names as it is added to the local namespace.
# Python3 code to demonstrate dir()
# when no parameters are passed to dir()
# Note that we have not imported any modules
print(dir())
# when modules are imported
import random
import math
# in this case dir() returns the module names added to the localnamespace
print(dir())
Output
[' __annotations__', ' __builtins__', ' __cached__', ' __doc__', ' __file__',
' __loader__', ' __name__', ' __package__', ' __spec__']
[' __annotations__', ' __builtins__', ' __cached__', ' __doc__', ' __file__',
' __loader__', ' __name__', ' __package__', ' __spec__', 'math', 'random']
Example 3: When a module object is passed as a parameter?
# Python3 code to demonstrate dir()
# when module objects are passed to dir()
import random
import math
print(dir(random))
print(dir(math))
Output
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST',
'SystemRandom', 'TWOPI', '_Sequence', '_Set', ' __all__', ' __builtins__',
' __cached__', ' __doc__', ' __file__', ' __loader__', ' __name__', ' __package__',
' __spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp',
'_floor', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin',
'_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate',
'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits',
'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randbytes',
'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle',
'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
[' __doc__', ' __loader__', ' __name__', ' __package__', ' __spec__', 'acos', 'acosh',
'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos',
'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs',
'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf',
'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma',
'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow',
'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau',
'trunc', 'ulp']
Example 4: dir() on User-defined Object
# Python3 code to demonstrate dir()
# on user defined object
class Employee:
# Function __dir()___ which list all
# the base attributes to be used.
def __dir__ (self):
return ['Id', 'FirstName', 'LastName', 'Salary','JoiningDate']
# user-defined object of class Employee
emp = Employee()
# listing out the dir() method for the userdefined object
print(dir(emp))
Output
['FirstName', 'Id', 'JoiningDate', 'LastName', 'Salary']
Conclusion
The dir()
function will help mainly in debugging the application. In the case of the large project, it will be really useful for developers when handling a lot of classes and functions separately, and dir()
will list out all the attributes of the object passed to it.
The post Python dir() appeared first on ItsMyCode.
Posted on October 19, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.