danijar
danijar

Reputation: 34215

How can I set up an alias for imports in Python?

I want my project to work in two different situations. It should work as a standalone library, but also as sub package of a larger project. The main use case is that of a standalone library, where its internal imports should be of the form

from my_library import sub_package

When using the code as sub package of a larger project, these imports don't work as there is no global name my_library. Instead, I would have to use relative or absolute imports, for example

from large_project.my_library import sub_package

Let's assume I wrote my library as shown in the first example. How can I overwrite importing behavior when running as part of a larger project to automatically adjust import paths?

Upvotes: 2

Views: 5078

Answers (2)

danijar
danijar

Reputation: 34215

Thanks to @MatrixTai's suggestion of adding the parent directory of the package to the the module path, I came up with this dynamic solution. At the top of my_library/__init__.py:

# Make package global even if used as a sub package to enable short imports.
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

We have to navigate up two directories here to do from the my_library/__init__.py to my_library and from there to its parent direction, where imports will find the library.

Upvotes: 4

MatrixTXT
MatrixTXT

Reputation: 2502

You don't have much choice.

If you want to reference the my_library.py anywhere, there is 2 method (as I known) can do similar work.


1: add system path. Like those module you installed by pip. pip module is installed in /Python/Scripts. You can add a new path or simply put my_library.py into one of the path. For adding, that's in Computer(right-click)-> Properties -> Environment Variable -> Choose Path and Click Edit

(Though you may not want to use this.)


2: Changing __init__.py, but still at least one line you must add in my_library.py.

For example,

/Directory
   /large_project
      -__init__.py #call this sub_init
      -my_library.py
   -__init__.py #call this main_init, this fake
   -main.py

In main_init,

import sys
sys.path.append('\\Directory\\large_project')

As main_init is not executed when you execute main.py (this is fake), so in main.py

import __init__
from my_library import sub_package

But as well you can take this main_init as the starter of library, like declaring __all__, etc.

Upvotes: 1

Related Questions