Michael
Michael

Reputation: 7809

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 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...

Upvotes: 4

Views: 481

Answers (2)

bakkal
bakkal

Reputation: 55448

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>

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

Then can use as follows

import syntax
b = syntax.Block()
l = syntax.List()

Upvotes: 6

FunkySayu
FunkySayu

Reputation: 8061

The most readable way to deal with that is to do your imports into the __init__.py file

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 the relative import syntax in your __init__.py file (for example from .List import List)


When you do an import, you define a variable. This variable is containing your imported variable, constant, function, class or whatever you want.

If you do from .List import List into your __init__.py file, you are defining the variable List into your __init__.py file refering to the class syntax.List.List.

So when you are trying you write from syntax import List you are trying to import the variable List from your __init__.py file, which point to the syntax.List.List.

from syntax import List
from syntax.List import List as OriginList

List is OriginList # True

Upvotes: 5

Related Questions