Python __dir__() Magic Method

Python’s __dir__() magic method implements the functionality of the dir() built-in function. Semantically, dir() returns all (function, object, or variable) names in a given scope. However, the magic method __dir__() converts any return value to a sorted list.

Minimal Example

The following code defines a custom class My_Class and overrides the __dir__() magic method to return a dummy list [1, 2, 3] when calling dir(x) an object x of type My_Class.

class My_Class:
    def __dir__(self):
        return [1, 2, 3]


x = My_Class()
print(dir(x))
# [1, 2, 3]

Before we dive into some more advanced examples, let’s have a look at the purpose of the dir() function first!

Background dir()

If used without argument, Python’s built-in dir() function returns the function and variable names defined in the local scope—the namespace of your current module.

If used with an object argument, dir(object) returns a list of attribute and method names defined in the object’s scope.

Python dir() Visual Explanation

Python __dir__() Sorted Output

The output of any dir() function call must be a sorted list (source). Even if you override it by defining your custom magic method __dir__(), Python will attempt to convert your custom output to a sorted list.

You can see this in the following example where your custom __dir__() returns an unsorted list—and Python brings it back to order!

class My_Class:
    def __dir__(self):
        return ['Bob', 'Alice', 'Carl']


x = My_Class()
print(dir(x))
# ['Alice', 'Bob', 'Carl']

The original list ['Bob', 'Alice', 'Carl'] was automatically and implicitly converted to the sorted list ['Alice', 'Bob', 'Carl'].

Python __dir__() List Elements of Different Type

If __dir__() returns a list with elements of different types—that is—types with incompatible comparison operators (<, >, <=, >=), Python will raise a TypeError: '<' not supported between instances of 'x' and 'y'.

class My_Class:
    def __dir__(self):
        return ['Bob', 'Alice', 42]


x = My_Class()
print(dir(x))

Output:

Traceback (most recent call last):
  File "C:\Users\...\code.py", line 7, in <module>
    print(dir(x))
TypeError: '<' not supported between instances of 'int' and 'str'

To fix the error, make sure that all elements in the list have compatible comparison operators.

You can accomplish this by defining the magic methods __lt__, __gt__, __ge__, and __le__ so that comparison of the diverse types is possible.

Alternatively, you can make sure that all elements of the list returned by __dir__ are of the same type.

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!