I am attempting to create a package (mypackage) that contains a few classes, but would like the classes contained in multiple files.
For example, I want class_a.py to contain a class named ClassA, etc...
Thus, I would like the following file structure:
.../mypackage
__init__.py
class_a.py
class_b.py
...
However, I would like to load and use the package as follows:
load mypackage
a = mypackage.ClassA()
What do I need to do (I assume in the __init__.py) file to make this possible. Currently, it operates using "mypackage.class_a.ClassA()"?
The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.
In the __init__.py file of a package __all__ is a list of strings with the names of public modules or other objects. Those features are available to wildcard imports. As with modules, __all__ customizes the * when wildcard-importing from the package.
Creating Packages Whenever you want to create a package, then you have to include __init__.py file in the directory. You can write code inside or leave it as blank as your wish. It doesn't bothers Python. Create a directory and include a __init__.py file in it to tell Python that the current directory is a package.
Create a file __init__.py and place it inside directory science so that it can be considered a Python package. Create sub-directories physics, chemistry, and biology and place __init__.py inside each sub-directories so that they can be considered Python sub-packages.
As mentioned, in your __init__.py
for a class, use the following:
from class_a import ClassA
from class_b import ClassB
for the case of a file without a class, use the following:
from . import file_a
from . import file_b
or if you only want to expose specific methods of a file:
from .file_a import method_a
from .file_b import method_b
Make your __init__.py
import all your ClassA
, ClassB
, etc from other files.
Then you'll be able to import mypackage
and use mypackage.ClassA
, or from mypackage import ClassA
and use it as unqualified ClassA
.
A bit of background.
An import foo
statement looks for foo.py
, then for foo/__init__.py
, and loads the names defined in that file into the current namespace. Put whatever you need to be "top-level" into __init__.py
.
Also, take a look at __all__
top-level variable if you tend to from mypackage import *
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With