>>> import module1
>>> dir(module1)
['__builtins__', '__doc__', '__file__', '__name__', '__package__']
I try putting some functions like this to module1 code:
def __dir__(self):
return 'ok'
def __dir__():
return 'ok'
def __dir__(self):
print 'ok'
def __dir__():
print 'ok'
… but nothing of those works. How good writen overwriting dir function should look?
I want something like this:
>>> import module1
>>> dir(module1)
'ok' [or ok]
Your question is asking how to modify the behavior of
dir()on module objects, but in your comments you clarified that your ultimate goal is to modify the behavior ofhelp(module).dirworks differently on different objects, and I don’t believe there is a direct way to change that for a module. It will simply always want to list the attributes of the module being everything in the scope.What you can do though, is define an
__all__attribute in your module, and specify which attributes should be made public in the help doc:mymodule
You will see that because
Klasswas excluded from__all__it will not be visible in the help.Also, if you do
from mymodule import *, only the foo attribute will be imported: