Dynamically updating the PYTHONPATH prevents .pyc update

梦想与她 提交于 2019-12-02 14:33:04

问题


To allow myself to have a clear filestructure in my project i am using the following code snippet to dynamically add the project main folder to the PYTHONPATH and therefore assure that I can import files even from above a files location.

import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "."))

Since I did this, when I start my main file, changes to the modules aren't recognized anymore until i manually delete any .pyc files. Thus I assume this for some reason prevented python from checking if the pyc files are up to date. Can I overcome this issue in any way?


回答1:


Adding the path of an already imported module can get you into trouble if module names are no longer unique. Consider that you do import foo, which adds its parent package bar to sys.path - it's now possible to also do import bar.foo. Python will consider both to be different modules, which can mess up anything relying on module identity.

You should really consider why you need to do this hack in the first place. If you have an executable placed inside your package, you should not do

cd bardir/bar
python foo

but instead call it as part of the package via

cd bardir
python -m bar.foo



回答2:


You could try to make python not write those *.pyc files.

How to avoid .pyc files?

For large projects this would matter slightly from a performance perspective. It's possible that you don't care about that, and then you can just not create the pyc files.



来源:https://stackoverflow.com/questions/39932498/dynamically-updating-the-pythonpath-prevents-pyc-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!