Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of absolute/relative paths in python stack trace

Tags:

python

I ran top_level_script.py and got an exception with a stack trace like:

File "top_level_script.py", line 114, in main
  …
File "top_level_script.py", line 91, in func1
  ...
File "top_level_script.py", line 68, in func2
  **kwargs)
File "/home/max/.../cccc/ffff/mmmm.py", line 69, in some_func
  obj = SomeClass(…)
File "mmm/ttt/bbb/core.py", line 17, in __init__
File "/home/max/.../pppp/pppp.py", line 474, in func
  ...
File "/home/max/.../pppp/pppp.py", line 355, in some_func
  ...

Notice that mmm/ttt/bbb/core.py has a relative path while the frame above and below it have absolute paths. Also, there is no print out of line 17, in __init__, and the code being called was "old". I just changed it, but old code was getting called. Hence the exception.

I still find the Python's import mechanic sometimes confusing. Can anyone elucidate what's up with core.py and what is the significance, if any, of the relative path shown in that frame?

After some tinkering, my hypothesis was that python was somehow calling the .pyc (hence no source shown in the line below). After tinkering with the file (i.e. changing and saving it), I now get:

File "top_level_script.py", line 114, in main
  …
File "top_level_script.py", line 91, in func1
  ...
File "top_level_script.py", line 68, in func2
  **kwargs)
File "/home/max/.../cccc/ffff/mmmm.py", line 69, in some_func
  obj = SomeClass(…)
File "/home/max/.../mmm/ttt/bbb/core.py", line 17, in __init__
  ...
File "/home/max/.../pppp/pppp.py", line 474, in func
  ...
File "/home/max/.../pppp/pppp.py", line 355, in some_func
  ...

Now, I can't reproduce the effect but I am still curious if anyone knows what may have happened.

like image 252
Max Avatar asked Mar 15 '13 21:03

Max


1 Answers

In general, Python is being transparent about how it understands the name of the file.

Whenever Python performs an import, the environment variable PYTHONPATH is consulted and that sets the Python variable sys.path.

Path components insys.path can be absolute or relative. A common relative path name is . (the current working directory).

If while performing the import, the name found in sys.path is based on a relative path, then the file name that appears in the stack trace will also be relative. I also think that if a Python program uses a relative import then that too appears as a relative file name.

like image 57
rocky Avatar answered Sep 23 '22 05:09

rocky