Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Import package modules before as well as after setup.py install

Assume a Python package (e.g., MyPackage) that consists of several modules (e.g., MyModule1.py and MyModule2.py) and a set of unittests (e.g., in MyPackage_test.py).

.
├── MyPackage
│   ├── __init__.py
│   ├── MyModule1.py
│   └── MyModule2.py
├── README.md
├── requirements.txt
├── setup.py
└── tests
    └── MyPackage_test.py

I would like to import functions of MyModule1.py within the unittests of MyPackage_test.py. Specifically, I would like to import the functions both before as well as after package installation via setup.py install MyPackage.

Currently, I am using two separate commands, depending on the state before or after package installation:

# BEFORE
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'MyPackage'))

# AFTER
import MyPackage

Can this be done with a single command?

like image 360
Michael G Avatar asked Dec 06 '18 10:12

Michael G


People also ask

How do I install Python packages from setup py?

Installing Python Packages with Setup.py To install a package that includes a setup.py file, open a command or terminal window and: cd into the root directory where setup.py is located. Enter: python setup.py install.

Does init py import all modules?

We can turn this directory into a package by introducing __init__.py file within utils folder. Within __init__.py , we import all the modules that we think are necessary for our project.

Does the order of imports matter in Python?

Import order does not matter. If a module relies on other modules, it needs to import them itself. Python treats each . py file as a self-contained unit as far as what's visible in that file.

Does pip need setup py?

As a first step, pip needs to get metadata about a package (name, version, dependencies, and more). It collects this by calling setup.py egg_info . The egg_info command generates the metadata for the package, which pip can then consume and proceed to gather all the dependencies of the package.


1 Answers

Option 1:

It seems that the following command does what I need:

sys.path.append(os.path.join(__file__.split(__info__)[0] + __info__), __info__)

Option 2:

Depending on the location of __init__.py, this also works:

sys.path.append(os.path.dirname(os.path.split(inspect.getfile(MyPackage))[0]))

Option 3:

Moreover, the ResourceManager API seems to offer additional methods.

like image 84
Michael G Avatar answered Oct 04 '22 09:10

Michael G