I'm currently creating a framework for a syntax tree. I have a folder/package syntax
which contains one syntax tree element which is a class in each file, the structure looks then like:
syntax/List.py -> contains class List
syntax/Block.py -> contains class Block
syntax/Statement.py -> contains class Statement
Now I'd like to import the folder into my source file in a way that I can access the classes like
block = syntax.Block()
Is that possible at all? So far, I always ended up that I need syntax.Block.Block()
which is not very nice...
Project structure
syntax
├── Block.py
├── __init__.py
The class
# syntax/Block.py (this file really ought to be lowercase, leave PascalCase to class names)
class Block(object):
pass
Imports in __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>
Unlike languages that require us to put a single class into a file with same name (class Block
inside file Block.py
), Python is pretty flexible about this.
You can actually put many classes in syntax.py
and import syntax
alone, then access syntax.Block
(no imports in __init__.py
would be required for this)
# syntax.py
class Block(object):
pass
class List(object):
pass
Then can use as follows
import syntax
b = syntax.Block()
l = syntax.List()
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