4

Importing sibling directories in Python

 2 years ago
source link: https://twilblog.github.io/python/python2.7/2017/05/26/python-imports.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Importing sibling directories in Python

Posted on May 26, 2017

shaun avatar broken :(

Shaun Donnelly

Please note that I’m referring to Python 2.x here, not Python 3.x.

I have a simple Python project laid out like this:

my-project/
    src/
        __init__.py
        main.py
    tests/
        test_main.py

I’d like to use test_main.py to test main.py (unsurprisingly). But how do I import main.py into my test? If you’re a NodeJS fanboy like myself, you might think you can do something like this:

import '../src/main'

Right? WRONG. Take your sensible, Bash style imports back to Nodeland, you glorified jQuery developer.

In Python, you need to do two things. First, create a blank __init__.py file inside tests/. This makes it into a package or something. Then, you can use this syntax to import the file:

from src import main

And then you’re good.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK