简体   繁体   中英

Importing from cousin module in Python

I have the following structure:

  • LICENSE.md
  • README.md
  • requirements.txt
  • src
    • routes
      • route_a.py
      • __ init __.py
    • util
      • __ init __.py
      • db.py

And in db.py, I have something that looks like this:

import mysql.connector

def get_value():
    # Query database using mysql.connector
    return value

value = get_value()

def query_that_uses_value(value):
     # do stuff with value
     return value2

I want to be able to use value inside of route_a.py and also inside of other functions in db.py . What's the best way to do this?

import sys   
sys.path.insert(0, "path")

that's how I did it. the path is the folder u want to use I would choose the main folder so u have the same starting point for your imports.

in your case, the import would look like this

from util.dp.py import get_value 

if you have this at the start of your programme that u want the function imported to

sys.path.insert(0,"path_to_src/src")

but path to src must be an absolut path beginning from your root folder

In route_a.py , simply import the variable value (and other functions you need) from ..util.db , which is a relative import that will reference src/util/db.py . Here's what the file src/routes/route_a.py should contain:

from ..util.db import value, function1, function2

Best way to deal with imports is to export PYTHONPATH=${PWD} in your project root directory where there are src , requirements.txt , etc.

So in your terminal, run export PYTHONPATH=${PWD} and all your imports should be consistent and start from src .

For example: from src.util.db import value from src.routes.route_a import something

Note that everytime you open a new terminal you should run export PYTHONPATH=${PWD} cause this is not permanent. When your terminal disappears your PYTHONPATH should reset and that's a good thing and is best practice.

Also don't forget to run everything from src . Like: python src/util/db.py

If you follow this structure, I promise you will never have any import problems.

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