Reputation: 1883
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()"?
Upvotes: 14
Views: 11342
Reputation: 5984
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
Upvotes: 5
Reputation: 869
In your __init__.py
, add this:
from class_a import ClassA
from class_b import ClassB
del class_a
del class_b
Upvotes: -1
Reputation: 40894
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 *
.
Upvotes: 1