nested_scopes with execfile

Mohammed Lazreg mxl at fluent.com
Tue Mar 19 14:17:39 EST 2002


Here is what I believe is happening:

when the interpreter enters the code block of f2 and finds f1 name, it
tries to resolve it using the nearest enclosing scope. So if you execute
Test2.py alone it will work because the enclosing scope is Test2.py
itself which does define f1 , but when you try to load Test2.py from
Test1.py the nearest enclosing scope of f2 scope is Test1.py which does
not define f1, hence the error....

If you change your Test2.py to this, it will works in both cases:

-----------------
def f1():
    print "OK it works"
def f2(arg):
    arg()

f2(f1)
----------------

$ ../Python-2.2/python Test2.py
OK it works
$ ../Python-2.2/python Test1.py
OK it works


Mohamed

Amir Hadar wrote:

> Hi
>
> I've encountered a problem when executing a file within a function:
>
> #----- Test1.py ------------------
> from __future__ import nested_scopes
>
> def f():
>     execfile("Test2.py")
>
> f()
> # EOF Test1.py -------------------
>
> #--------Test2.py ----------------
> def f1():
>     print "OK it works"
> def f2():
>     f1()
>
> f2()
> #EOF Test2.py --------------------
>
> When executing the Test1.py the following error is displayed:
> Traceback (most recent call last):
>   File "<string>", line 1, in ?
>   File "C:\PROGRA~1\Python22\Test1.py", line 6, in ?
>     f()
>   File "C:\PROGRA~1\Python22\Test1.py", line 4, in f
>     execfile("Test2.py");
>   File "Test2.py", line 8, in ?
>     f2()
>   File "Test2.py", line 6, in f2
>     f1()
> NameError: global name 'f1' is not defined
>
> The reson that I need this is because I want to make a "Load" funtion
> that will execute the given file (e.g. Load("Yada.py")) and then will
> run a function in that file (e.g. def Init():).
>
> In the example I gave the second file ("Test2.py") is loaded to the
> local environment of the function f() in the first file (Test1.py).
> Therefore the functions f1 and f2 are in that env. Now, When f2 calls
> f1 it should resolve its variables in the enclosing environment which
> is the env of f (Test1.py) but it doen't.
>
> Help Me.
>          Amir.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
> --
> This message has been 'sanitized'.  This means that potentially
> dangerous content has been rewritten or removed.  The following
> log describes which actions were taken.
>
> [ score: 10 ]
> 00189   Split long word(s) in header.
>
> Anomy 0.0.0 : sanitizer.pl
> $Id: sanitizer.pl,v 1.35 2001/02/01 00:10:46 bre Exp $





More information about the Python-list mailing list