Dunder methods

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the python category.

Last Updated: 2024-11-23

Start and finish with double underscore __x__

Show were a module is found of file system

import rest_framework as rf
print(rf.__path__[0]))
'/Users/jk/.virtualenvs/myproject/lib/python3.10/site-packages/rest_framework'

What happens if reversed

You can define backwards iteration using __reversed__ e.g.

What happens if stringified

Use __repr__

What happens in iterations

Use __iter__ in general and __next__ to get subsequent item

Module name

If you import a file as a module, Python sets the module name to the name variable.

So below we having billing.py

def calculate_tax(price, tax):
    return price * tax


print(__name__)

If importing from anothe file, you will see billing printed

Howver in scripts, it can be used to detect if the script file was called

if __name__ == "__main__":
    unittest.main()

Array-like access and setting


def __getitem__(self, key):
    return self.get(key)

def __setitem__(self, key, value):
    return self.put(key, value)