简体   繁体   中英

Override installed module in import

I am currently working on a package that's nearly ready for distribution. As such, I'm trying out installing it (via setup.py ) on my system. However, I also need access to the current (source code) package, eg for tests.

Is it possible to explicitly force importing the local package instead of the installed version? What I already tried is adding the path at the beginning of sys.paths , with no luck.

I guess this question goes into how exactly Python looks for the modules to import, and how to change the order.

EDIT : It was a silly mistake, adding at the beginning of sys.paths works. I had some other import statement elsewhere that was executed first.

  1. This is bad bad idea to do something like force importing the local package .

  2. Python3 always import the built-in modules first, and obviously you're using Python3 cause Python2 is local-first.

  3. I don't know how to solve this problem, if I were you I'd rename that file.

edit

You don't use append cause append is to the end. Use insert . Tested on my cpu. I created a requests.py in another folder.

>>> import sys
>>> sys.path.insert(0 ,"path-to-another-folder/")
>>> import requests
>>> requests.get
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'get'
>>>

If I don't do sys.path.insert(0 ,"path-to-another-folder/") , requests is imported normally.

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