Reputation: 6147
If I have a module folder structure like this:
studio
tools
__init__.py
camera
__init__.py
camera.py
element
__init__.py
element.py
How do I write the __init__.py files to make it so I can write my import statements like the following? There is a class object in the camera
module called CameraNode
that I would like to call like shown in the sample below.
from studio import tools
tools.camera.fn()
tools.CameraNode('')
tools.element.fn()
Upvotes: 13
Views: 37862
Reputation: 1481
An __init__.py
file allows you to treat any directory as a Python package. It is not necessary to write anything in the file itself, just creating it in your directory is enough.
So camera
, element
, and tools
can behave as packages.
However, if you want to access Python files in sub-directories as well, then you must import those in the __init__.py
of the parent directory.
For example, if you want to do tools.camera
then you must import camera
in the __init__.py
in the tools directory.
Otherwise, you will have to import camera
separately to access all of the functions in it.
Upvotes: 12
Reputation: 21918
If you have a studio/tools/__init__.py
file like this:
from .camera import *
from .element import *
Then you can do a single import elsewhere like:
from studio import tools
and then reference everything as if it were directly in studio.tools.
Not sure if this is answering your question exactly, but hopefully it gets you going in the right direction.
Upvotes: 17