369

I've tried reading through questions about sibling imports and even the package documentation, but I've yet to find an answer.

With the following structure:

├── LICENSE.md
├── README.md
├── api
│   ├── __init__.py
│   ├── api.py
│   └── api_key.py
├── examples
│   ├── __init__.py
│   ├── example_one.py
│   └── example_two.py
└── tests
│   ├── __init__.py
│   └── test_one.py

How can the scripts in the examples and tests directories import from the api module and be run from the commandline?

Also, I'd like to avoid the ugly sys.path.insert hack for every file. Surely this can be done in Python, right?

CharlesB
  • 86,532
  • 28
  • 194
  • 218
zachwill
  • 4,395
  • 3
  • 19
  • 17
  • 14
    I recommend skipping past all the `sys.path` hacks and reading [the only actual *solution*](https://stackoverflow.com/a/50193944/1222951) that's been posted thus far (after 7 years!). – Aran-Fey Nov 02 '18 at 10:32
  • 2
    By the way, there's still room for another good solution: Separating executable code from library code; most of the time a script inside a package shouldn't *be* executable to begin with. – Aran-Fey Nov 02 '18 at 10:46
  • This is so helpful, both the question and the answers. I am just curious, how come "Accepted Answer" is not the same as the one awarded the bounty in this case? – Indominus Dec 27 '18 at 21:41
  • 1
    @Aran-Fey That's an underrated reminder in these relative import error Q&As. I've been looking for a hack this whole time, but deep down I knew there was a simple way to design my way out of the problem. Not to say that it's the solution for everyone here reading, but it's a good reminder as it could be for many. – colorlace Apr 19 '19 at 22:10

18 Answers18

404

Tired of sys.path hacks?

There are plenty of sys.path.append -hacks available, but I found an alternative way of solving the problem in hand.

Summary

  • Wrap the code into one folder (e.g. packaged_stuff)
  • Create setup.py script where you use setuptools.setup(). (see minimal setup.py below)
  • Pip install the package in editable state with pip install -e <myproject_folder>
  • Import using from packaged_stuff.modulename import function_name

Setup

The starting point is the file structure you have provided, wrapped in a folder called myproject.

.
└── myproject
    ├── api
    │   ├── api_key.py
    │   ├── api.py
    │   └── __init__.py
    ├── examples
    │   ├── example_one.py
    │   ├── example_two.py
    │   └── __init__.py
    ├── LICENCE.md
    ├── README.md
    └── tests
        ├── __init__.py
        └── test_one.py

I will call the . the root folder, and in my example case it is located at C:\tmp\test_imports\.

api.py

As a test case, let's use the following ./api/api.py

def function_from_api():
    return 'I am the return value from api.api!'

test_one.py

from api.api import function_from_api

def test_function():
    print(function_from_api())

if __name__ == '__main__':
    test_function()

Try to run test_one:

PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
Traceback (most recent call last):
  File ".\myproject\tests\test_one.py", line 1, in <module>
    from api.api import function_from_api
ModuleNotFoundError: No module named 'api'

Also trying relative imports wont work:

Using from ..api.api import function_from_api would result into

PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
Traceback (most recent call last):
  File ".\tests\test_one.py", line 1, in <module>
    from ..api.api import function_from_api
ValueError: attempted relative import beyond top-level package

Steps

  1. Make a setup.py file to the root level directory

The contents for the setup.py would be*

from setuptools import setup, find_packages

setup(name='myproject', version='1.0', packages=find_packages())
  1. Use a virtual environment

If you are familiar with virtual environments, activate one, and skip to the next step. Usage of virtual environments are not absolutely required, but they will really help you out in the long run (when you have more than 1 project ongoing..). The most basic steps are (run in the root folder)

  • Create virtual env
    • python -m venv venv
  • Activate virtual env
    • source ./venv/bin/activate (Linux, macOS) or ./venv/Scripts/activate (Win)

To learn more about this, just Google out "python virtual env tutorial" or similar. You probably never need any other commands than creating, activating and deactivating.

Once you have made and activated a virtual environment, your console should give the name of the virtual environment in parenthesis

PS C:\tmp\test_imports> python -m venv venv
PS C:\tmp\test_imports> .\venv\Scripts\activate
(venv) PS C:\tmp\test_imports>

and your folder tree should look like this**

.
├── myproject
│   ├── api
│   │   ├── api_key.py
│   │   ├── api.py
│   │   └── __init__.py
│   ├── examples
│   │   ├── example_one.py
│   │   ├── example_two.py
│   │   └── __init__.py
│   ├── LICENCE.md
│   ├── README.md
│   └── tests
│       ├── __init__.py
│       └── test_one.py
├── setup.py
└── venv
    ├── Include
    ├── Lib
    ├── pyvenv.cfg
    └── Scripts [87 entries exceeds filelimit, not opening dir]
  1. pip install your project in editable state

Install your top level package myproject using pip. The trick is to use the -e flag when doing the install. This way it is installed in an editable state, and all the edits made to the .py files will be automatically included in the installed package.

In the root directory, run

pip install -e . (note the dot, it stands for "current directory")

You can also see that it is installed by using pip freeze

(venv) PS C:\tmp\test_imports> pip install -e .
Obtaining file:///C:/tmp/test_imports
Installing collected packages: myproject
  Running setup.py develop for myproject
Successfully installed myproject
(venv) PS C:\tmp\test_imports> pip freeze
myproject==1.0
  1. Add myproject. into your imports

Note that you will have to add myproject. only into imports that would not work otherwise. Imports that worked without the setup.py & pip install will work still work fine. See an example below.


Test the solution

Now, let's test the solution using api.py defined above, and test_one.py defined below.

test_one.py

from myproject.api.api import function_from_api

def test_function():
    print(function_from_api())

if __name__ == '__main__':
    test_function()

running the test

(venv) PS C:\tmp\test_imports> python .\myproject\tests\test_one.py
I am the return value from api.api!

* See the setuptools docs for more verbose setup.py examples.

** In reality, you could put your virtual environment anywhere on your hard disk.

Niko Föhr
  • 28,336
  • 10
  • 93
  • 96
  • 27
    Thanks for the detailed post. Here is my problem. If I do everything you said and I do a pip freeze, I get a line `-e git+https://username@bitbucket.org/folder/myproject.git@f65466656XXXXX#egg=myproject` Any Idea on how to resolve? – Si Mon Dec 11 '18 at 16:42
  • 8
    Why doesn't the relative import solution work? I believe you, but I'm trying to understand Python's convoluted system. – Jared Nielsen Feb 01 '19 at 02:56
  • 1
    I have not digged into this so deeply to understand *why* it does not work; I just see that relative imports beyond top-level package are not allowed. I have also noticed that making pip-installable packages out of my python packages/apps have made my python experience better. But that's of course very subjective :) – Niko Föhr Feb 01 '19 at 08:59
  • Good answer but it's unclear why `setup.py` is required? – DRz Aug 27 '19 at 14:29
  • You need the `setup.py` to make your python code a pip-installable python package. – Niko Föhr Aug 28 '19 at 06:48
  • 33
    Has anyone has problems with regards to a `ModuleNotFoundError`? I've installed 'myproject' into a virtualenv following these steps, and when I enter an interpreted session and run `import myproject` I get `ModuleNotFoundError: No module named 'myproject'`? `pip list installed | grep myproject` shows that it is there, the directory is correct, and both the verison of `pip` and `python` are verified to be correct. – ThoseKind Aug 28 '19 at 14:40
  • 3
    To fix the problem, at least for me, make sure the directory containing all the code has the same name as what you've called it in `setup.py` - for me, this was my `src` directory. – platelminto Sep 11 '19 at 02:47
  • It works but it prints following(4 times) while importing from sibling directory to console. `None {'name': 'MyProject', 'path': None} ` . Same class when imported from current directory doesn't print anything – ishandutta2007 Sep 15 '19 at 22:24
  • Soo.. How does this works? I finally made it work, but I do not fully understand, I can import my Package, but if I do `pip freeze` It is not on list – Grzegorz Krug Oct 31 '19 at 01:21
  • 1
    @GrzegorzKrug: Is the `pip` command pointing to the right `pip` executable? Does `python -m pip freeze` give the same results? – Niko Föhr Oct 31 '19 at 09:36
  • 2
    Hey @np8, it works, I accidentally installed it in venv and in os :) `pip list` shows packages, while `pip freeze` shows weird names if installed with flag **-e** – Grzegorz Krug Nov 03 '19 at 17:11
  • @np8 Hey, I have encountered similar issue and I have made sure I did everything as you said in the post. Could you have a look at this [thread](https://stackoverflow.com/q/58896546/7784797)? – Mr.Robot Nov 17 '19 at 00:48
  • 6
    Spent about 2 hours trying to figure out how to make relative imports work, and this answer was the one that finally actually did something sensible. – Graham Lea Nov 28 '19 at 04:29
  • 5
    @ThoseKind I also encured same problem, `pip freeze` have the same output with you. After caerfully read this anwser, I found my directory structure is wrong. Please note that `.` at this anwser's directory structure, the setup.py is at the same level with `myproject`, not inside the `myproject` folder, I put setup.py in the `myproject` by mistake, after move setup.py out, everything works. – Li Jinyao Feb 01 '20 at 11:56
  • 37
    What I think is sickening is that I have to come to stackoverflow to find a real answer on how to do relative imports correctly. The documentation around this stuff really needs to be improved. – teuber789 Feb 20 '20 at 17:21
  • [PEP 517](https://www.python.org/dev/peps/pep-0517/) does not support editable installs as noted on [setuptools](https://setuptools.readthedocs.io/en/latest/setuptools.html?highlight=517#setup-cfg-only-projects) . What is the safest, most flexible way of adding directories to python lookup path? I'd like to avoid sys.path and pythonpath hacks, and so far this is the best answer. – DanielTuzes May 12 '21 at 10:21
  • 1
    @DanielTuzes I think this is a question which is broad enough to be posted as a standalone question on SO – Niko Föhr May 12 '21 at 12:01
  • 1
    What specifically is responsible in adding the root package to the path in this procedure? For me it's working on one machine but not the other. Python can be so much fun.... – CervEd May 21 '21 at 13:23
  • 1
    In my case the suggested methods works well. but my question is how this code will be deployed. is it through the python pip package ? which can be installed only through pip install ? I need more clarification if anyone can help here. – nillu Jun 17 '21 at 06:39
  • Do you have to do pip installs every time your code / directory structure changes, ethough? – Joe Flack May 27 '23 at 21:03
  • 1
    @Joe Flack if using the -e flag you only install once and changes to code are reflected automatically. – Niko Föhr May 27 '23 at 21:07
  • I am getting `ModuleNotFoundError: No module named 'api'` even though `findpackages()` returns `['myproject.api', ...]` – scrollout Aug 17 '23 at 17:28
  • @scrollout you need to `import myproject.api` or `from myproject import api`. – sinoroc Aug 17 '23 at 17:37
  • @sinoroc the issue was my module was called `helpers`. To test this, I renamed it to `helpers2` and it worked. – scrollout Aug 17 '23 at 18:21
  • I had same issue as @ThoseKind and kept getting error: `ModuleNotFoundError: No module named 'myproject'`. I fixed the issue by creating a virtual environment using `virtualenv` instead of using `venv`. I don't understand why I get different results based on the method used to create the virtual environment. Note: I use VS Code to test my code. – Zythyr Aug 28 '23 at 20:51
117

Seven years after

Since I wrote the answer below, modifying sys.path is still a quick-and-dirty trick that works well for private scripts, but there has been several improvements

  • Installing the package (in a virtualenv or not) will give you what you want, though I would suggest using pip to do it rather than using setuptools directly (and using setup.cfg to store the metadata)
  • Using the -m flag and running as a package works too (but will turn out a bit awkward if you want to convert your working directory into an installable package).
  • For the tests, specifically, pytest is able to find the api package in this situation and takes care of the sys.path hacks for you

So it really depends on what you want to do. In your case, though, since it seems that your goal is to make a proper package at some point, installing through pip -e is probably your best bet, even if it is not perfect yet.

Old answer

As already stated elsewhere, the awful truth is that you have to do ugly hacks to allow imports from siblings modules or parents package from a __main__ module. The issue is detailed in PEP 366. PEP 3122 attempted to handle imports in a more rational way but Guido has rejected it one the account of

The only use case seems to be running scripts that happen to be living inside a module's directory, which I've always seen as an antipattern.

(here)

Though, I use this pattern on a regular basis with

# Ugly hack to allow absolute import from the root folder
# whatever its name is. Please forgive the heresy.
if __name__ == "__main__" and __package__ is None:
    from sys import path
    from os.path import dirname as dir

    path.append(dir(path[0]))
    __package__ = "examples"

import api

Here path[0] is your running script's parent folder and dir(path[0]) your top level folder.

I have still not been able to use relative imports with this, though, but it does allow absolute imports from the top level (in your example api's parent folder).

Evpok
  • 4,273
  • 3
  • 34
  • 46
  • 4
    you don't *have to* if you [run from a project directory using `-m` form or if you install the package](http://stackoverflow.com/a/23542795/4279) (pip and virtualenv make it easy) – jfs May 08 '14 at 13:15
  • 4
    How does pytest find the api package for you? Amusingly, I found this thread because I'm running into this problem specifically with pytest and sibling package importing. – JuniorIncanter Jan 18 '19 at 00:30
  • 1
    I have two questions, please. 1. Your pattern seems to work without `__package__ = "examples"` for me. Why do you use it? 2. In what situation is `__name__ == "__main__"` but `__package__` is not `None`? – actual_panda Nov 06 '19 at 16:57
  • @actual_panda Setting `__packages__` helps if you want absolute path such as `examples.api` to work iirc (but it has been a long time since I last did that) and checking that package is not None was mostly a failsafe for weird situations and futureproofing. – Evpok Jan 30 '20 at 10:48
  • 1
    Gosh, if only other languages would make the same process as easy as it is in Python. I see why everyone loves this language. Btw, documentation is also excellent. I love extracting return types from unstructured text, it's a nice change from Javadoc and phpdoc. ffs.... – matt Jul 08 '20 at 16:04
  • @JuniorIncanter two years late, but [here's the documentation](https://docs.pytest.org/en/stable/goodpractices.html#choosing-a-test-layout-import-rules) – Mike C Sep 28 '20 at 18:38
  • @Evpok Would you mind elaborating on how to install it without setuptools? – Llohann Aug 22 '23 at 13:58
50

Here is another alternative that I insert at top of the Python files in tests folder:

# Path hack.
import sys, os
sys.path.insert(0, os.path.abspath('..'))
Trang Oul
  • 134
  • 1
  • 8
Cenk Alti
  • 2,792
  • 2
  • 26
  • 25
  • 1
    +1 really simple and it worked perfectly. You need to add the parent class to the import (ex api.api, examples.example_two) but I prefer it that way. – Evan Plaice Jun 01 '12 at 21:35
  • 14
    I think it's worth mentioning to newbies (like myself) that `..` here is relative to the directory you're executing from---not the directory containing that test/example file. I'm executing from the project directory, and I needed `./` instead. Hope this helps someone else. –  May 23 '18 at 18:01
  • @JoshDetwiler, yes absoluely. I was not aware of that. Thanks. – doak Jan 31 '19 at 11:12
  • 6
    This is a poor answer. Hacking the path is not good practice; it's scandalous how much it's used in the python world. One of the main points of this question was to see how imports could be done while avoiding this kind of hack. – teuber789 Feb 20 '20 at 17:20
  • 2
    `sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))` @JoshuaDetwiler – vldbnc May 15 '20 at 18:27
  • @teuber789 I don't see anything wrong with using this approach in dev to allow developers to quickly test things out and decide to move code around etc. This approach is absolutely acceptable for early-stage projects or bigger rewrites as a mechanism. – Zenahr Jan 08 '22 at 23:35
44

You don't need and shouldn't hack sys.path unless it is necessary and in this case it is not. Use:

import api.api_key # in tests, examples

Run from the project directory: python -m tests.test_one.

You should probably move tests (if they are api's unittests) inside api and run python -m api.test to run all tests (assuming there is __main__.py) or python -m api.test.test_one to run test_one instead.

You could also remove __init__.py from examples (it is not a Python package) and run the examples in a virtualenv where api is installed e.g., pip install -e . in a virtualenv would install inplace api package if you have proper setup.py.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • @Alex the answer does not assume that tests are API tests *except* for the paragraph where it says explicitly *"if they are api's unittests"*. – jfs Nov 24 '16 at 20:30
  • unfortunately then you are stuck with running from root dir and PyCharm still does not find the file for its nice functions – mhstnsc Nov 03 '17 at 17:28
  • 1
    @mhstnsc: it is not correct. You should be able to run `python -m api.test.test_one` from anywhere when the virtualenv is activated. If you can't configure PyCharm to run your tests, try to ask a new Stack Overflow question (if you can't find an existing question on this topic). – jfs Nov 03 '17 at 18:05
  • @jfs I missed the virtual env path but i don't want to use anything more than shebang line to run this stuff from any directory ever. Its not about running with PyCharm. Devs with PyCharm would know also they have completion and jump through functions which i could not make it work with any solution. – mhstnsc Nov 03 '17 at 20:48
  • 1
    @mhstnsc an appropriate shebang is enough in many cases (point it to the virtualenv python binary. Any decent Python IDE should support a virtualenv. – jfs Sep 25 '18 at 19:43
12

I don't yet have the comprehension of Pythonology necessary to see the intended way of sharing code amongst unrelated projects without a sibling/relative import hack. Until that day, this is my solution. For examples or tests to import stuff from ..\api, it would look like:

import sys.path
import os.path
# Import from sibling directory ..\api
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
import api.api
import api.api_key
user1330131
  • 137
  • 1
  • 2
  • This would still give you the api parent directory and you wouldn't need the "/.." concatenation sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) – Camilo Sanchez Jul 23 '14 at 03:46
8

For readers in 2023: If you're not confident with pip install -e :

TL;DR: A script(usually an entry point) can only import anything the same or below its level.

Consider this hierarchy, as recommended by an answer from Relative imports in Python 3:

MyProject
├── src
│   ├── bot
│   │   ├── __init__.py
│   │   ├── main.py
│   │   └── sib1.py
│   └── mod
│       ├── __init__.py
│       └── module1.py
└── main.py

To run our program from the starting point with the simple command python main.py, we use absolute import (no leading dot(s)) in main.py here:

from src.bot import main


if __name__ == '__main__':
    main.magic_tricks()

The content of bot/main.py, which takes advantage of explicit relative imports to show what we're importing, looks like this:

from .sib1 import my_drink                # Both are explicit-relative-imports.
from ..mod.module1 import relative_magic

def magic_tricks():
    # Using sub-magic
    relative_magic(in=["newbie", "pain"], advice="cheer_up")
    
    my_drink()
    # Do your work
    ...

These are the reasonings:

  • We don't want to give "OK, so this is a module" a funk when we want to run our Python program, sincerely.
    • So we use absolute import for the entry point main.py, this way we can run our program by simply python main.py.
    • Behind the scene, Python will use sys.path to resolve packages for us, but this also means that the package we want to import can probably be superseded by any other package of the same name due to the ordering of paths in sys.path e.g. try import test.
  • To avoid those conflicts, we use explicit relative import.
    • The from ..mod syntax makes it very clear about "we're importing our own local package".
    • But the drawback is that you need to think about "OK, so this is a module" again when you want to run the module as a script.
  • Finally, the from ..mod part means that it will go up one level to MyProject/src.

Conclusion

  1. Put your main.py script next to the root of all your packages MyProject/src, and use absolute import in python main.py to import anything. No one will create a package named src.
  2. Those explicit relative imports will just work.
  3. To run a module, use python -m ....

Appendix: More about running any file under src/ as a script?

Then you should use the syntax python -m and take a look at my other post: ModuleNotFoundError: No module named 'sib1'

NeoZoom.lua
  • 2,269
  • 4
  • 30
  • 64
  • This actually worked for me. I think without this "src" directory/package, the subpackages didn't have common root package. – stoper May 08 '23 at 16:58
  • @stoper Thanks for your feedback. I'm very proud to say that no one can beat my explanation here. I read a lot of answers and came up with this myself. – NeoZoom.lua May 08 '23 at 23:28
6

For siblings package imports, you can use either the insert or the append method of the [sys.path][2] module:

if __name__ == '__main__' and if __package__ is None:
    import sys
    from os import path
    sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
    import api

This will work if you are launching your scripts as follows:

python examples/example_one.py
python tests/test_one.py

On the other hand, you can also use the relative import:

if __name__ == '__main__' and if __package__ is not None:
    import ..api.api

In this case you will have to launch your script with the '-m' argument (note that, in this case, you must not give the '.py' extension):

python -m packageName.examples.example_one
python -m packageName.tests.test_one

Of course, you can mix the two approaches, so that your script will work no matter how it is called:

if __name__ == '__main__':
    if __package__ is None:
        import sys
        from os import path
        sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
        import api
    else:
        import ..api.api
Paolo Rovelli
  • 9,396
  • 2
  • 58
  • 37
  • I was using the Click framework which doesn't have the `__file__` global so I had to use the following: `sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0]))))` But it works in any directory now – GammaGames Mar 08 '19 at 15:39
  • 1
    There are no good answers to this. And shows how the makers of python must live in some fantasy bubble where a relative import is just almost impossible. – C.J. Apr 21 '21 at 18:03
3

TLDR

This method does not require setuptools, path hacks, additional command line arguments, or specifying the top level of the package in every single file of your project.

Just make a script in the parent directory of whatever your are calling to be your __main__ and run everything from there. For further explanation continue reading.

Explanation

This can be accomplished without hacking a new path together, extra command line args, or adding code to each of your programs to recognize its siblings.

The reason this fails as I believe was mentioned before is the programs being called have their __name__ set as __main__. When this occurs the script being called accepts itself to be on the top level of the package and refuses to recognize scripts in sibling directories.

However, everything under the top level of the directory will still recognize ANYTHING ELSE under the top level. This means the ONLY thing you have to do to get files in sibling directories to recognize/utilize each other is to call them from a script in their parent directory.

Proof of Concept In a dir with the following structure:

.
|__Main.py
|
|__Siblings
   |
   |___sib1
   |   |
   |   |__call.py
   |
   |___sib2
       |
       |__callsib.py

Main.py contains the following code:

import sib1.call as call


def main():
    call.Call()


if __name__ == '__main__':
    main()

sib1/call.py contains:

import sib2.callsib as callsib


def Call():
    callsib.CallSib()


if __name__ == '__main__':
    Call()

and sib2/callsib.py contains:

def CallSib():
    print("Got Called")

if __name__ == '__main__':
    CallSib()

If you reproduce this example you will notice that calling Main.py will result in "Got Called" being printed as is defined in sib2/callsib.py even though sib2/callsib.py got called through sib1/call.py. However if one were to directly call sib1/call.py (after making appropriate changes to the imports) it throws an exception. Even though it worked when called by the script in its parent directory, it will not work if it believes itself to be on the top level of the package.

Thunderwood
  • 525
  • 2
  • 9
  • The OP specifically asked for "How can the scripts in the `examples` and `tests` directories import from the `api` module and *be run from the commandline*?" This answer will not work with the OPs folder structure. – Niko Föhr Jul 20 '20 at 07:29
  • You don't need main.py file; instead of executing the command the `python main.py` which calls the `sib1.call`, you can execute `python -m sib1.call`. – Ersel Er Aug 03 '20 at 00:23
  • I run into an issue where `ImportError: No module named sib1.call` – Evan Gertis Mar 12 '21 at 20:41
2

You need to look to see how the import statements are written in the related code. If examples/example_one.py uses the following import statement:

import api.api

...then it expects the root directory of the project to be in the system path.

The easiest way to support this without any hacks (as you put it) would be to run the examples from the top level directory, like this:

PYTHONPATH=$PYTHONPATH:. python examples/example_one.py 
AJ.
  • 27,586
  • 18
  • 84
  • 94
  • With Python 2.7.1 I get the following: `$ python examples/example.py Traceback (most recent call last): File "examples/example.py", line 3, in from api.api import API ImportError: No module named api.api`. I also get the same with `import api.api`. – zachwill Jun 12 '11 at 18:51
  • Updated my answer...you **do** have to add the current directory to the import path, no way around that. – AJ. Jun 12 '11 at 18:58
2

If you're using pytest then the pytest docs describe a method of how to reference source packages from a separate test package.

The suggested project directory structure is:

setup.py
src/
    mypkg/
        __init__.py
        app.py
        view.py
tests/
    __init__.py
    foo/
        __init__.py
        test_view.py
    bar/
        __init__.py
        test_view.py

Contents of the setup.py file:

from setuptools import setup, find_packages

setup(name="PACKAGENAME", packages=find_packages())

Install the packages in editable mode:

pip install -e .

The pytest article references this blog post by Ionel Cristian Mărieș.

John
  • 1,043
  • 15
  • 20
1

Just in case someone using Pydev on Eclipse end up here: you can add the sibling's parent path (and thus the calling module's parent) as an external library folder using Project->Properties and setting External Libraries under the left menu Pydev-PYTHONPATH. Then you can import from your sibling, e. g. from sibling import some_class.

Lord Henry Wotton
  • 1,332
  • 1
  • 10
  • 11
1

I made a sample project to demonstrate how I handled this, which is indeed another sys.path hack as indicated above. Python Sibling Import Example, which relies on:

if __name__ == '__main__': import os import sys sys.path.append(os.getcwd())

This seems to be pretty effective so long as your working directory remains at the root of the Python project.

ADataGMan
  • 449
  • 1
  • 7
  • 23
1

I wanted to comment on the solution provided by np8 but I don't have enough reputation so I'll just mention that you can create a setup.py file exactly as they suggested, and then do pipenv install --dev -e . from the project root directory to turn it into an editable dependency. Then your absolute imports will work e.g. from api.api import foo and you don't have to mess around with system-wide installations.

Documentation

jerry_
  • 310
  • 4
  • 5
0

in your main file add this:

import sys
import os 
sys.path.append(os.path.abspath(os.path.join(__file__,mainScriptDepth)))

mainScriptDepth = the depth of the main file from the root of the project.

Here is your case mainScriptDepth = "../../". Then you can import by specifying the path (from api.api import * ) from the root of your project.

akash
  • 727
  • 5
  • 13
-1

The problem:

You simply can not get import mypackage to work in test.py. You will need either an editable install, change to path, or changes to __name__ and path

demo
├── dev
│   └── test.py
└── src
    └── mypackage
        ├── __init__.py
        └── module_of_mypackage.py

--------------------------------------------------------------
ValueError: attempted relative import beyond top-level package

The solution:

import sys; sys.path += [sys.path[0][:-3]+"src"]

Put the above before attempting imports in test.py. Thats it. You can now import mypackage.

This will work both on Windows and Linux. It will also not care from which path you run your script. It is short enough to slap it anywhere you might need it.

Why it works:

The sys.path contains the places, in order, where to look for packages when attempting imports if they are not found in installed site packages. When you run test.py the first item in sys.path will be something like /mnt/c/Users/username/Desktop/demo/dev i.e.: where you ran your file. The oneliner will simply add the sibling folder to path and everything works. You will not have to worry about Windows vs Linux file paths since we are only editing the last folder name and nothing else. If you project structure is already set in stone for your repository we can also reasonably just use the magic number 3 to slice away dev and substitute src

-2

for the main question:

call sibling folder as module:

from .. import siblingfolder

call a_file.py from sibling folder as module:

from ..siblingfolder import a_file

call a_function inside a file in sibling folder as module:

from..siblingmodule.a_file import func_name_exists_in_a_file

The easiest way.

go to lib/site-packages folder.

if exists 'easy_install.pth' file, just edit it and add your directory that you have script that you want make it as module.

if not exists, just make it one...and put your folder that you want there

after you add it..., python will be automatically perceive that folder as similar like site-packages and you can call every script from that folder or subfolder as a module.

i wrote this by my phone, and hard to set it to make everyone comfortable to read.

Wahyu Bram
  • 413
  • 1
  • 7
  • 13
-4
  1. Project

1.1 User

1.1.1 about.py

1.1.2 init.py

1.2 Tech

1.2.1 info.py

1.1.2 init.py

Now, if you want to access about.py module in the User package, from the info.py module in Tech package then you have to bring the cmd (in windows) path to Project i.e. **C:\Users\Personal\Desktop\Project>**as per the above Package example. And from this path you have to enter, python -m Package_name.module_name For example for the above Package we have to do,

C:\Users\Personal\Desktop\Project>python -m Tech.info

Imp Points

  1. Don't use .py extension after info module i.e. python -m Tech.info.py
  2. Enter this, where the siblings packages are in the same level.
  3. -m is the flag, to check about it you can type from the cmd python --help
Achyut Pal
  • 39
  • 3
-4

First, you should avoid having files with the same name as the module itself. It may break other imports.

When you import a file, first the interpreter checks the current directory and then searchs global directories.

Inside examples or tests you can call:

from ..api import api
  • I get the following with Python 2.7.1: `Traceback (most recent call last): File "example_one.py", line 3, in from ..api import api ValueError: Attempted relative import in non-package` – zachwill Jun 12 '11 at 20:35
  • 2
    Oh, then you should add a `__init__.py` file to the top level directory. Otherwise Python can't treat it as a module –  Jun 13 '11 at 00:03
  • 9
    It won't work. The issue is not that the parent folder is not a package, it is that since the module's `__name__` is `__main__` instead of `package.module`, Python can't see its parent package, so `.` points to nothing. – Evpok Jun 24 '11 at 10:00