简体   繁体   中英

Confused with python import (absolute and relative)

I created project and helper modules for it. But some of modules are using each other like worker 1 uses helper1 and helper2 also uses helper1. So I completle confused how I need to import all those modules so so can work standalone (for example I want to debug helper2 out of main script) and they still will be functional. Summarizing - how to correctly import modules so maint_script will work and other modules when using out of main_script. Sorry for my English.

 main program dir/ main_script.py -classes/ | |--helper1.py |--helper2.py -worker_classes/ | |--worker1.py

At the moment I'am using this constructions in the begging of each script, but I feel that this approach isn't appropriate for python

import os
import sys

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'shell_modules')))

The way I deal with imports inside a project is to install the project in editable mode. This way, all files will be able to locate each other, always starting from your project root directory.

In order to do this, follow these steps:

1) write a setup.py file and add it to your project root folder - it doesn't need much info at all:

# setup.py
from setuptools import setup, find_packages

setup(name='MyPackageName', version='1.0.0', packages=find_packages())

2) install your package in editable mode (ideally from a virtual environment). From a terminal in your project folder, write

$ pip install -e .

Note the dot - this means "install the package from the current directory in editable mode".

3) your files are now able to locate each other, always starting from the project root. To import helper1.py , for example, you write:

from classes import helper1

or alternatively:

from classes.helper1 import foo, bar

This will be true to import helper1.py for any file, no matter where it is located in the project structure.

Like I said, you should use a virtual environment for this, so that pip does not install your package to your main Python installation (which could be messy if your project has many dependencies).

Currently my favorite tool for this is pipenv . When using it, replace the terminal command with

$ pipenv install -e .

So that your project gets added to the Pipfile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM