Pythonista Cookbook: Difference between revisions

From Littledamien Wiki
Jump to navigation Jump to search
(Created page with "[Category:Python] == Locating modules in parent directories == Given a project structure like this: <pre> | +- my_module/ | | | +- test/ | | | | | +- test_some_pkg.py | | | |...")
(No difference)

Revision as of 10:41, 12 January 2018

[Category:Python]

Locating modules in parent directories

Given a project structure like this:

|
+- my_module/
| |
| +- test/
| | |
| | +- test_some_pkg.py
| | |
| | +- [etc...]
| |
| +- some_pkg.py
| |
| +- [etc...}
|
+- some_top_level_file.py
|
+- [etc...]

In my_module/test/test_some_pkg.py some_pkg is imported with:

from my_module import some_pkg

If you have my_module/test/test_pkg_a.py open in Pythonista and try to run it, you'll get an error that it doesn't know anything about my_module.

(By contrast, in PyCharm, you can specify the base path of the project in the Run settings which will avoid this.)

In order to get around this in Pythonista, add the top-level path to PYTHONPATH by adding this before importing some_pkg:

import sys; sys.path.append('../../')

That line should be removed before committing any changes to git. It won't break anything, it's just unnecessary in any other context.