Some code of mine sprung a bug seemingly out of nowhere. When I tracked it down, I found that evaluating inspect.getmodule
with the same (identical) argument before and after executing os.chdir
gives different results.
(FWIW, I'm running Python 2.7.3, under OS X.)
I find this behavior so puzzling and bewildering that I don't know how best to fix the bug. (In other words, with understanding the reason for the behavior, anything solution I can think of is only a band-aid.)
The test script below illustrates the behavior (although, of course, the real-life bug occurred in a far more realistic and complex context):
import inspect
import os
def prn(line, mod):
print ('getmodule called at line %2d; returned module: %-8s (id: %d)' %
(line - 1, getattr(mod, '__name__', mod), id(mod)))
fr = inspect.currentframe()
mod = inspect.getmodule(fr) # line 10
prn(fr.f_lineno, mod)
mod = inspect.getmodule(fr) # line 13
prn(fr.f_lineno, mod)
os.chdir('subdir')
mod = inspect.getmodule(fr) # line 18
prn(fr.f_lineno, mod)
(NOTE: running this code requires that there be a subdirectory called "subdir" immediately under the current directory.)
Its output is:
getmodule called at line 10; returned module: __main__ (id: 4297636784)
getmodule called at line 13; returned module: __main__ (id: 4297636784)
getmodule called at line 18; returned module: None (id: 4296513024)
Note that, although all three calls to getmodule
have the same frame object as argument, the result of the last one differs from the results produced the first two. (The results from the first two calls are identical, as one would expect.)
The only difference between the first two calls and the third one is that the latter takes place after running os.chdir
.
Any insight on what's going on would be appreciated.