Why is __dir __ () not working for a module in python?

test_module.py:

def __dir__():
    return ['test']

my_module.py:

import test_module
print dir(test_module)

The expected result should be ['test'], but actually the result:

['__builtins__', '__dir__', '__doc__', '__file__', '__name__', '__package__']

why does the client itself __dir__()not work?

+4
source share
1 answer

Why do you need to limit what is specified for a module? dir()- debugging tool, basically.

Magic methods usually look for the type of object, so they dir()look for instances type(instance).__dir__. Your function is not a type module, but rather a module instance. However, you cannot extend the type module, so you cannot provide the module with its own method __dir__.

from yourmodule import *, __all__; , , . . import.

+4

All Articles