I have following files and directories in my project root directory
main.py
bar.py
foo \
__init__.py
alice.py
bob.py
the files in directory foo are all empty files, and the content of bar.py is
alice = None
bob = None
and main.py is
import foo
import bar
print 'foo:', dir(foo)
print 'bar:', dir(bar)
When execute python main.py the output is
foo: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
bar: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'alice', 'bob']
Why there is no alice or bob in foo? And, what should I do other than
from foo import alice, bob
if I want to use alice and bob of the module foo, since there might be a lot of files in that folder?
EDIT
My question is not about the built-in function dir giving weird result. If I do this in main.py
import foo
foo.alice
An exception will occur: AttributeError: ‘module’ object has no attribute ‘alice’
There seems no alice in foo? I think I have some problem understanding how to import a directory as a module.
It basically comes down to the difference between a module and a package. From the docs:
The purpose of the
__init__.pyfile within a directory is to make it a package. This file provides a place specify the public facing interface for the package. There’s two ways you can getaliceandbobintofoo:1. Use
__all__In your
__init__.pyfile, you can explicitly declare what modules you want to expose with__all__. The following will exposealiceandbob.2. import
aliceandbobdirectlyAlternatively, importing the modules within the
__init__.pyfile will also expose these modules.It will also import these modules at initialization time, so whenever you import anything in foo they will also get imported.