Skip subdirectory in python import

Posted by jstaab on Stack Overflow See other posts from Stack Overflow or by jstaab
Published on 2014-06-02T21:15:30Z Indexed on 2014/06/02 21:26 UTC
Read the original article Hit count: 156

Filed under:
|

Ok, so I'm trying to change this:

app/
    - lib.py
    - models.py
    - blah.py

Into this:

app/
    - __init__.py
    - lib.py
    - models/
        - __init__.py
        - user.py
        - account.py
        - banana.py
    - blah.py

And still be able to import my models using from app.models import User rather than having to change it to from app.models.user import User all over the place. Basically, I want everything to treat the package as a single module, but be able to navigate the code in separate files for development ease.

The reason I can't do something like add for file in __all__: from file import * into init.py is I have circular references between the model files. A fix I don't want is to import those models from within the functions that use them. But that's super ugly. Let me give you an example:

user.py

...
from app.models import Banana
...

banana.py

...
from app.models import User
...

I wrote a quick pre-processing script that grabs all the files, re-writes them to put imports at the top, and puts it into models.py, but that's hardly an improvement, since now my stack traces don't show the line number I actually need to change.

Any ideas? I always though init was probably magical but now that I dig into it, I can't find anything that lets me provide myself this really simple convenience.

© Stack Overflow or respective owner

Related posts about python

Related posts about import