6

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?

Michael Gruenstaeudl
  • 1,609
  • 1
  • 17
  • 31
  • May not be exactly what you want but take a look at `python setup.py develop`. – Justin Fay Dec 10 '18 at 10:10
  • I do not think this is possible, unless the entry point of the script is the directory with the setup.py file in it. Also refer to [this](https://stackoverflow.com/questions/4383571/importing-files-from-different-folder) post for more info. – Nikolaos Paschos Dec 10 '18 at 10:43
  • These look like two different imports to me. When extending the `sys.path`, you shouldn't be able to import `MyPackage` at all, only being able to import `MyModule1` etc. What is your original issue? Are you unable to import your package in the tests? – hoefling Dec 11 '18 at 09:22
  • Interesting question. I'm curious why you would want to do this though. Why would you want to run the unit tests after the package as already been installed? – Karl Dec 14 '18 at 20:22

2 Answers2

2

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.

Michael Gruenstaeudl
  • 1,609
  • 1
  • 17
  • 31
0

in pycharm IDE you can can import method easily.by setting the working directory to the folder which contains all files.
And, then in MyPackage __init__.py file import all the function from MyModule1.py and MyModule2.py .
then in MyPackage_test.py you can use

import MyPackage 
from MyPackage import xyz
sahasrara62
  • 10,069
  • 3
  • 29
  • 44