简体   繁体   中英

Importing modules that import other modules from other directories in Python 3.6

I have a working directory that looks like this:

project
  src
    data
      +secrets.py
      +data.py
    +format.py

I have variables in secrets.py called user and pw .

I import the variables in data.py to connect to a database like so:

from secrets import user, pw

This works, but now I want to be able to run this from within format.py :

from data.data import <function_name>

I get an Import Error: cannot import name 'user' from 'secrets'

Since format.py is not in the same directory as data.py , the import is breaking because it cannot find a secrets.py . If I were to update data.py with this:

from data.secrets import user, pw

I could successfully run format.py . But then that would break data.py !

I feel like I am just completely structuring my project wrong from the jump. Is there are better way to do this or a way to fix the import errors?

I have tried using relative imports with .. and explicitly using src.data.secrets but that will still break data.py

Try from.secrets import user, pw . I tried, it works. The dot means you are importing module from the current directory

This should work.

from importlib import import_module

format = import_module("../format.py")

You may have to use and probably should according to the docs.

from importlib import import_module

format = exec_module(create_module(find_spec("../format.py)))

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