Convenient to import multiple classes from modules in a Python package
I am currently creating a structure for a syntax tree. I have a folder / package syntax
that contains one syntax tree item which is a class in each file, the structure looks like then:
syntax/List.py -> contains class List
syntax/Block.py -> contains class Block
syntax/Statement.py -> contains class Statement
Now I would like to import the folder into the source file in such a way that the classes can be accessed like
block = syntax.Block()
Is this even possible? Until now I have always ended up with what I need syntax.Block.Block()
, which is not very pleasant ...
source to share
Project structure
syntax
βββ Block.py
βββ __init__.py
Class
# syntax/Block.py (this file really ought to be lowercase, leave PascalCase to class names)
class Block(object):
pass
Import to __init__
# syntax/__init__.py
from .Block import Block # Relative import with .
Using the package
In [5]: import syntax
In [6]: b = syntax.Block()
In [7]: b
Out[7]: <syntax.Block.Block at 0x108dcb990>
Alternative if you are open to any kind of reorganization
Unlike languages ββthat require us to put one class in a file with the same name (a class Block
within a file Block.py
), Python is quite flexible about this.
You can put many classes in syntax.py
and import only syntax
, then access syntax.Block
(it doesn't require import in __init__.py
)
# syntax.py
class Block(object):
pass
class List(object):
pass
Then can be used as follows
import syntax b = syntax.Block() l = syntax.List()
source to share
The most readable way to deal with this is to do the import to a file __init__.py
Example:
# syntax/__init__.py
from syntax.List import List
from syntax.Block import Block
from syntax.Statement import Statement
# in your main file
from syntax import List
import syntax
b = syntax.Block()
Note. You can also use relative import syntax in your file __init__.py
(for example from .List import List
)
When you import, you are defining a variable. This variable contains your imported variable, constant, function, class, or whatever.
If you are doing from .List import List
to your __init__.py
file, you are defining the variable List
to your file __init__.py
by referencing the class syntax.List.List
.
So when you try to write from syntax import List
, you are trying to import a variable List
from your file __init__.py
that points to syntax.List.List
.
from syntax import List
from syntax.List import List as OriginList
List is OriginList # True
source to share