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?
If module
adoes afrom b import Foo, thenFoois a member ofaafterwards and accessible asa.Foo. It’s only consequent that you can now import it too usingfrom 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
foowith the following layout:a.py,b.py,c.py, define the classesA,BandC, respectively.If you wanted to use those classes, you’d normally have to write
This has at least two problems:
So normally you just put the following in the
__init__.py:Now you put all the pieces together in a single place and all of the classes are accessible with one import: