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
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.
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.
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.
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.
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. [...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With