Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: alias for relative import

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
like image 487
flotzilla Avatar asked Jul 14 '15 10:07

flotzilla


People also ask

How do you use relative import in Python?

Relative imports use dot(.) notation to specify a location. A single dot specifies that the module is in the current directory, two dots indicate that the module is in its parent directory of the current location and three dots indicate that it is in the grandparent directory and so on.

Should I use relative or absolute imports Python?

With your new skills, you can confidently import packages and modules from the Python standard library, third party packages, and your own local packages. Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long.

How can you alias a module in Python?

Having multiple version of a Python package/module/file is very common. Manipulating PYTHONPATH or using virtualenvs are a way to use various versions without changing your code.

Should I use relative imports Python?

Because there, they want to make sure that other developers could also get the full path of the import module. Relative imports are helpful when you are working alone on a Python project, or the module is in the same directory where you are importing the module.


1 Answers

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. [...]

like image 183
tynn Avatar answered Oct 11 '22 21:10

tynn