Michael Michael - 1 year ago 58
Python Question

Conveniently import several classes from modules in a Python package

I'm currently creating a framework for a syntax tree. I have a folder/package

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
which is not very nice...

Answer Source

Project structure

├── Block.py
├── __init__.py

The class

# syntax/Block.py (this file really ought to be lowercase, leave PascalCase to class names)
class Block(object):

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>

Alternative if you are open to some re-organization

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):
class List(object):

Then can use as follows

import syntax
b = syntax.Block()
l = syntax.List()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download