__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.
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
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!
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__() 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
__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))
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.
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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.