Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python __dir__() Magic Method

#1
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!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!



https://www.sickgaming.net/blog/2021/12/...ic-method/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

[-]
Discord

[-]
Active Threads
(Indie Deal) The GameCreators 2 Bundle, ...
Last Post: xSicKxBot
Today 08:59 AM
» Replies: 0
» Views: 41
(Free Game Key) Free DLC for Steam game ...
Last Post: xSicKxBot
Today 08:59 AM
» Replies: 0
» Views: 4
Microsoft - 4 approaches to comprehensiv...
Last Post: xSicKxBot
Today 08:59 AM
» Replies: 0
» Views: 4
News - Review: Pinchcliffe Grand Prix – ...
Last Post: xSicKxBot
Today 08:58 AM
» Replies: 0
» Views: 6
News - GTA Online Adds New Double Down M...
Last Post: xSicKxBot
Today 08:58 AM
» Replies: 0
» Views: 9
[Tut] Python __set_name__() Magic Method
Last Post: xSicKxBot
Yesterday 07:31 PM
» Replies: 0
» Views: 69
Godot 3.5 Beta Released
Last Post: xSicKxBot
Yesterday 07:30 PM
» Replies: 0
» Views: 7
AppleInsider - Dutch App Store change al...
Last Post: xSicKxBot
Yesterday 07:30 PM
» Replies: 0
» Views: 7
Microsoft - EzPC: Increased data securit...
Last Post: xSicKxBot
Yesterday 07:30 PM
» Replies: 0
» Views: 7
News - Community Focus: GamerGirlGrey
Last Post: xSicKxBot
Yesterday 07:30 PM
» Replies: 0
» Views: 7

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com



Discord Server © SickGaming.net 2012-2021