0

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?

weidler
  • 676
  • 1
  • 6
  • 22

2 Answers2

2

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
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
1

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.

Community
  • 1
  • 1
vlad-ardelean
  • 7,480
  • 15
  • 80
  • 124
  • I will try this if there isnt any more elegant solution. Though i would like to understand why this is happening. – weidler Oct 08 '16 at 12:55
  • `sys.modules` contains the modules that were loaded by the interpreter. If you're modifying the PYTHONPATH and some new modules would override what was already there, then the new changes won't be seen - probably. You shouldn't be using magic like this anyway. Just set the PYTHONPATH to as high in the file hierarchy as possible, and be done with that. Also, you should be using virtualenv to install both your project and other dependencies there, and setup.py entry points for more complex stuff. Do you have a project which has grown out of a simiple script and you never refactored it? – vlad-ardelean Oct 08 '16 at 13:04