Search code examples
pythonstringclassmodulemagic-methods

What use is there for defining magic methods outside of a class?


What happens if I define a magic method outside a class?
For example, say I do:

def __str__(stuff):
    return "chicken"

directly inside the module.

When would something like this be useful? I thought it might be useful if I import this module named module1 elsewhere and try to do print(module1), but that just prints out the file location and other stuff.

So is there even any use for using a magic method outside a class? Is it even really a magic method any more?


Solution

  • At the moment (Python 3.9), two module-level magic methods can be defined: __getattr__ and __dir__ (see PEP 562 for details).

    • __getattr__ overrides attribute access on that module, including imports of the form from x import y.
    • __dir__ overrides what is returned by dir(module).

    For example:

    # foo.py
    
    def __getattr__(name):
        return name
    
    def __dir__():
        return ['foo', 'bar']
    

    Then we can use it in the following way:

    >>> import foo
    >>> dir(foo)
    ['bar', 'foo']
    >>> from foo import bar
    >>> bar
    'bar'