Skip subdirectory in python import
Question: 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.


Answer: It depends on what your circular references are for. If you have a class in
user that inherits from Banana and a class in banana that inherits from User,
you can't do this. You also can't do it if each class defines a decorator that
gets used in the other or anything else that gets called during the actual
import.

You can, however, if you are just mutually referencing helper functions, or if
your User object has a method to create new instances of Banana and your
Banana object has a method that creates new instances of User. As long as the
mutual reference doesn't actually get used until something in the module is
called from outside it, then in your model folder, in `__init__.py`, you can
just do something like:

    
    
    import user
    import banana
    #etc...
    user.banana = banana
    banana.user = user
    #etc...
    
    User = user.User
    Banana = banana.Banana
    

Then for sake of clarity and not trying to figure out what's going on

