Python dir()

Python dir() is a useful function for finding out what names (like variables, functions, and classes) are defined in a particular scope or for a specific object. Python dir() lists the names in your current local scope when called without arguments.
Table of Contents

Understanding Python dir() Function

Python dir() function is a built-in function that returns a list of valid attributes for a given object. If you call dir() without arguments, it returns a list of names in the current scope (like the variables and functions you’ve defined). When you pass an object to dir(), it inspects it and returns a sorted list of strings representing its attributes, including methods, variables, and other members. Python dir() is primarily used for debugging and interactive exploration, helping you discover what you can do with an object or what’s available in your current environment.

Syntax of Python dir()

list_of_attributes = dir(object)

Explanation

  • list_of_attributes: Variable will store the list of attribute names returned by dir().
  • dir(): Built-in function that inspects the object and returns its attributes.
  • object (optional): Object you want to inspect. It is the input for dir() function. If not provided, dir() returns names in the current scope.

Example of Python dir()

print(dir())

Explanation

  • print(dir()): Calls dir() without arguments to get the names in the current scope and then prints them.

Output

[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’]


dir() Parameters

Python dir() function can be called with or without a parameter. When called without any parameters, it returns a list of names in the current local scope. When called with an object as a parameter, it returns a list of valid attributes for that object. This object can be a module, a class, or any other object. dir() function examines the object’s attributes and methods and returns them as a sorted list of strings.

Syntax

list_of_attributes = dir(object)

Example

import math
print(dir(math))

Explanation

  • import math: Imports the math module.
  • print(dir(math)): Calls dir() with the math module as an argument and prints the resulting list of attributes.

Output

[‘__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’]


dir() Return Value

Python dir() function returns a sorted list of strings. When called without arguments, it returns names in the current local scope. When called with an object, it returns the names of the object’s attributes, including methods and variables. It’s important to note that dir() primarily aims to provide an interactive help feature, so the returned list might not always be exhaustive. Still, it will include the most relevant and useful names.

Example

class MyClass:
    def __init__(self):
        self.x = 10
        self.y = 20

    def my_method(self):
        pass

obj = MyClass()
print(dir(obj))

Explanation

  • class MyClass:: Defines a class named MyClass.
  • def __init__(self):: Constructor for MyClass.
  • self.x = 10: Initializes an attribute x to 10.
  • self.y = 20: Initializes an attribute y to 20.
  • def my_method(self):: Defines a method my_method.
  • pass: Placeholder, indicating that my_method doesn’t do anything.
  • obj = MyClass(): Creates an instance of MyClass.
  • print(dir(obj)): Calls dir() on obj and prints the list of its attributes.

Output

[‘__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__’, ‘my_method’, ‘x’, ‘y’]


Python dir() with a List Passed as Parameter

When you pass a list to Python dir(), it returns a sorted list of strings representing the available attributes and methods for list-objects. This includes built-in methods like append(), insert(), remove(), and others that you can use with lists. It also includes special methods (those with double underscores) that define how lists behave with operators and other language constructs.

Example

my_list = [1, 2, 3]
print(dir(my_list))

Explanation

  • my_list = [1, 2, 3]: Creates a list named my_list.
  • print(dir(my_list)): Calls dir() on my_list and prints the list of its attributes.

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’]


dir() with a Set Passed as Parameter

Passing a set to Python dir() returns a sorted list of strings representing the attributes and methods available for set objects. This includes methods like add(), remove(), union(), intersection(), and others that are specific to sets. Like other types, dir() also includes special methods that define how sets interact with Python’s operators and language features.

Example

my_set = {1, 2, 3}
print(dir(my_set))

Explanation

  • my_set = {1, 2, 3}: Creates a set named my_set.
  • print(dir(my_set)): Calls dir() on my_set and prints the list of its attributes.

Output

[‘__and__’, ‘__class__’, ‘__class_getitem__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__iand__’, ‘__init__’, ‘__init_subclass__’, ‘__ior__’, ‘__isub__’, ‘__iter__’, ‘__ixor__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__or__’, ‘__rand__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__ror__’, ‘__rsub__’, ‘__rxor__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__sub__’, ‘__subclasshook__’, ‘__xor__’, ‘add’, ‘clear’, ‘copy’, ‘difference’, ‘difference_update’, ‘discard’, ‘intersection’, ‘intersection_update’, ‘isdisjoint’, ‘issubset’, ‘issuperset’, ‘pop’, ‘remove’, ‘symmetric_difference’, ‘symmetric_difference_update’, ‘union’, ‘update’]


dir() with a Tuple Passed as Parameter

Passing a tuple to Python dir() returns a sorted list of strings representing the attributes and methods available for tuple objects. This includes methods like count() and index(), which are specific to tuples. As with other data types, dir() lists the special methods that define how tuples behave in various contexts.

Example

my_tuple = (1, 2, 3)
print(dir(my_tuple))

Explanation

  • my_tuple = (1, 2, 3): Creates a tuple named my_tuple.
  • print(dir(my_tuple)): Calls dir() on my_tuple and prints the list of its attributes.

Output

[‘__add__’, ‘__class__’, ‘__class_getitem__’, ‘__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’]


Python dir() with a User-defined Object Passed as Parameter

When you pass an instance of a user-defined class to Python dir(), it returns a list of attributes and methods associated with that object, including any you’ve defined in your class and built-in ones. This includes special methods like __init__, __str__, and others. dir() also includes the attributes and methods inherited from parent classes. This can be incredibly useful for understanding the structure and capabilities of your custom objects.

Example

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def my_method(self):
        pass

obj = MyClass(5, 10)
print(dir(obj))

Explanation

  • class MyClass:: Defines a class named MyClass.
  • def __init__(self, x, y):: Constructor for MyClass.
  • self.x = x: Initializes an attribute x.
  • self.y = y: Initializes an attribute y.
  • def my_method(self):: Defines a method my_method.
  • pass: Placeholder, as my_method doesn’t do anything in this example.
  • obj = MyClass(5, 10): Creates an instance of MyClass named obj.
  • print(dir(obj)): Calls dir() on obj and prints the list of its attributes.

Output

[‘__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__’, ‘my_method’, ‘x’, ‘y’]


Python dir() without argument

When you call Python dir() without any arguments, it returns a sorted list of names in the current local scope. This includes variables, functions, classes, and modules you’ve defined or imported in your current session or script. This can be very handy for interactive exploration, allowing you to see what names are available without remembering them.

Example

a = 10
b = "hello"

def my_function():
    pass

print(dir())

Explanation

  • a = 10: Defines a variable a.
  • b = "hello": Defines a variable b.
  • def my_function():: Defines a function my_function.
  • pass: Placeholder in the function definition.
  • print(dir()): Calls dir() without arguments and prints the list of names in the current scope.

Output

[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘a’, ‘b’, ‘my_function’]


Conclusion

Python dir() function is helpful for exploring and understanding Python objects and the current scope. It can be used with or without arguments to get a list of names in the current scope or associated with a specific object. While it’s primarily used for debugging and interactive exploration, understanding how Python dir works can give you deeper insights into Python’s object model and the structure of your code.


Also Read

Python dict()

Python divmod()


Python Reference

python dir()

Table of Contents