Scope (?) question

Peter peter.milliken at gmail.com
Tue Jun 15 20:58:01 EDT 2010


This one seems to do the trick - thanks! :-)

On Jun 16, 10:12 am, Inyeol Lee <inyeol.... at gmail.com> wrote:
> On Jun 15, 3:22 pm, Peter <peter.milli... at gmail.com> wrote:
>
>
>
>
>
> > I am puzzled by what appears to be a scope issue - obviously I have
> > something wrong :-)
>
> > Why does this work:
>
> > if __name__ == 'main':
> >   execfile('test-data.py')
> >   print data
>
> > and yet this doesn't (I get "NameError: global name 'data' not
> > defined"):
>
> > def X():
> >   execfile('test-data.py')
> >   print data
>
> > where test-data.py is:
>
> > data = [1,2,3,4]
>
> > I checked help on execfile and could only find the following
> > (mystifying) sentence:
>
> > "execfile() cannot be used reliably to modify a function’s locals."
>
> > Thanks
> > Peter
>
> This is due to CPython's static optimization of local name lookup.
> Dummy 'exec' statement disables this and makes your example work:
>
> def X():
>   exec "None"
>   execfile('test-data.py')
>   print data
>
> --inyeol




More information about the Python-list mailing list