简体   繁体   中英

How to force import module in Python 3?

I have two packages with structure like this:

Package1/calc1.py
Package1/utils.py

Package2/calc2.py
Package2/utils.py

calc1.py looks like this:

#calc1.py
import utils
...

and calc2.py looks the same:

#calc2.py
import utils
...

Also, I have the main module with main.py file. It starts like this:

import package1.calc1
import package2.calc2

After running main.py, I got the error:

ImportError: cannot import name 'utils'

It happens because when calc1.py import utils (from Package1), utils added to cache. So when it is time to import utils from Package2 by calc2.py, utils already in the cache and I got the error. These utils files a different and I can't rename them, they should have the same names, it is important.

The question is like that: are there any possible ways to force import modules to rewrite cache, or maybe clear module cache?

As others have pointed out, this has nothing to do with caching and has to do with your project structure. You should be using absolute path import or relative path import in your calc1.py and calc2.py modules. Here is an example:

Project Structure :

/
├ main.py
├ pkg1
│  ├ calc1.py
│  └ utils.py
└ pkg2
   ├ calc2.py
   └ utils.py

main.py :

import pkg1.calc1
import pkg2.calc2

pkg1.calc1.times5()
pkg2.calc2.times10()

calc1.py :

# absolute path import
from pkg1 import utils

def times5():
  print(utils.name)
  print(f'{utils.val} x 5 = {utils.val * 5}')

pkg1.utils.py :

name = 'using pkg1.utils.py'
val = 1

calc2.py :

# relative path import
from . import utils

def times10():
  print(utils.name)
  print(f'{utils.val} x 10 = {utils.val * 10}')

pkg2.utils.py :

name = 'using pkg2.utils.py'
val = 2

Output from main.py :

using pkg1.utils.py
1 x 5 = 5
using pkg2.utils.py
2 x 10 = 20

You can also read more on absolute vs relative imports here .

There is reload() function in imp / importlib module

For Python2.x

reload(module)

For above 2.x and <=Python3.3

import imp
imp.reload(module)

For >=Python3.4

import importlib
importlib.reload(module)

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