11

Is it possible to import a module of the same package with an alias using relative import?

Say I have the following package structure:

lib/
    foobar/
        __init__.py
        foo.py
        bar.py

And in foo.py, I'd like to use something from bar.py, but I'd like to use it as "bar.my_function", so instead of from .bar import my_function, I've tried import .bar as bar and import .bar, both of which don't work (invalid syntax exception). I've tried both pythhon2.7 and python3.4 (the latter being my target version).

However, what DOES work, and what I'm using now, is import foobar.bar as bar, i.e. absolute import instead of relative. It's an OK solution, given I don't expect the package name to change (and even if it does, there's not much to change in the code), but it would be nice if I could accomplish this using relative import!

Summary:

#import .bar as bar # why not?!?
#import .bar # shot in the dark
import foobar.bar as bar # current solution

1 Answer 1

18

You need to use

from . import bar

The documentation states concerning this

[...] you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. [...]

Sign up to request clarification or add additional context in comments.

2 Comments

Of course, should've realized that myself! facepalm But well, hindsight's easier than foresight. Thanks for your answer!
The new syntax also lets you apply an alias to the relatively-imported module, if you wish (e.g. if the module itself has a long-ish name). from . import long_module_name as bar (I spent a LONG time searching questions and documentation figuring that one out!). It's a little klunky compared to Python 2 when the implicit relative import let you just do import long_module_name as bar, but at least it's still available as an option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.