Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Importing object that originates in one module from a different module into a third module

Tags:

python

import

I was reading the sourcode for a python project and came across the following line:

from couchexport.export import Format

(source: https://github.com/wbnigeria/couchexport/blob/master/couchexport/views.py#L1 )

I went over to couchexport/export.py to see what Format was (Class? Dict? something else?). Unfortunately Format isn't in that file. export.py does however import a Format from couchexport.models where there is a Format class (source: https://github.com/wbnigeria/couchexport/blob/master/couchexport/models.py#L11).

When I open up the original file in my IDE and have it look up the declaration, in line I mentioned at the start of this question, it leads directly to models.py.

What's going on? How can an import from one file (export.py) actually be an import from another file (models.py) without being explicitly stated?

like image 939
adewinter Avatar asked Apr 07 '12 10:04

adewinter


1 Answers

If module a does a from b import Foo, then Foo is a member of a afterwards and accessible as a.Foo. It's only consequent that you can now import it too using from a import Foo.

This is commonly used if you have a large library distributed across multiple files and you want them to be accessible from a single location. Let's say you have a package foo with the following layout:

foo/
    a.py
    b.py
    c.py
    __init__.py

a.py, b.py, c.py, define the classes A, B and C, respectively.

If you wanted to use those classes, you'd normally have to write

from foo.a import A
from foo.b import B
from foo.c import C

This has at least two problems:

  1. Much code (three lines) is needed for this simple import
  2. The library author can now no longer change the file/class association afterwards, because that would break existing code.

So normally you just put the following in the __init__.py:

from a import A
from b import B
from c import C

Now you put all the pieces together in a single place and all of the classes are accessible with one import:

from foo import A,B,C
like image 56
Niklas B. Avatar answered Dec 09 '22 21:12

Niklas B.