comments on runpy module

Alexey Luchko luch at ank-sia.com
Fri Sep 23 20:21:56 CEST 2011


Hi!

I've just had fun with the runpy module in Python 2.7.  I'm writing to 
share it :)

What I've tried is to "load" a python script using runpy.run_path(), take a 
function from the resulting namespace and call it with arbitrary arguments.

All the functions in the namespace seem to be ok.  repr(namespace["f"]) 
gives "<function f at 0x005531F0>".

But if the f() is referring the modules namespace (I supposed it is the 
same as the returned one), all the values appear to be None.

Example script.py: """
def f(arg):
    return g(arg)

def g(arg):
    return arg
"""

Then running main.py: """
import runpy

namespace = runpy.run_path("./script.py")
print namespace["f"]
print namespace["g"]

print namespace["f"]("abc")
"""

gives such an output """
<function f at 0x005524F0>
<function g at 0x023F0830>
Traceback (most recent call last):
   File "main.py", line 7, in <module>
     print namespace["f"]("abc")
   File "./script.py", line 2, in f
     return g(arg)
TypeError: 'NoneType' object is not callable
"""

Reading the Lib/runpy.py I've found, that the temporary module created 
inside the run_path() calls, is destroyed right after the script.py code 
executed in the resulting namespace.

I suppose that it is ether an issue or a feature that should be documented :)

--
Have a good time and a good mood!

Alex.



More information about the Python-list mailing list