473,385 Members | 1,342 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Bug in execfile?

Hi all,

I'm finding the following behavior truly puzzling, but before I post a bug
report on the site, I'd rather be corrected if I'm just missing somethin
obvious.

Consider the following trivial script:

# Simple script that imports something from the stdlib
from math import sin, pi

wav = lambda k,x: sin(2*pi*k*x)

print wav(1,0.25)

# EOF
The above runs just fine from a prompt, or even interactively via execfile().
Now, consider calling it by using this instead:

#!/usr/bin/env python
"""Test for a bug (?) in scope handling by the execfile() builtin."""
def runscript(fname):
"""Run a file by calling execfile()."""
execfile(fname)
# Note: if you activate this section so that execfile() is directly called
# first, then the bug below disappears!!!
if 0:
print '='*80
print '# Trying execfile:'
execfile('execfilebugscript.py')

# The bug: we get an exception from running the little script, where the 'sin'
# name imported from math is not visible to the lambda.
print '-'*80
print '# Trying the runscript wrapper:'
runscript('execfilebugscript.py')

##### EOF
If I run the above, calling the first script 'execfilebugscript.py' and the
second 'execfilebug.py', I get this:

planck[test]./execfilebug.py
--------------------------------------------------------------------------------
# Trying the runscript wrapper:
Traceback (most recent call last):
File "./execfilebug.py", line 21, in <module>
runscript('execfilebugscript.py')
File "./execfilebug.py", line 7, in runscript
execfile(fname)
File "execfilebugscript.py", line 6, in <module>
print wav(1,0.25)
File "execfilebugscript.py", line 4, in <lambda>
wav = lambda k,x: sin(2*pi*k*x)
NameError: global name 'sin' is not defined
WTF??? Now even weirder, if the 'if 0' is turned into 'if 1' so that *first*
execfile is called at the top-level (not inside a function), then *both* calls
work:

planck[test]./execfilebug.py
================================================== ==============================
# Trying execfile:
1.0
--------------------------------------------------------------------------------
# Trying the runscript wrapper:
1.0
I'm really, really puzzled by this. From reading the execfile() docs, I had
the hunch to change the call to:

execfile(fname,{})

and now the problem disappears, so I can keep on working.

But I'm still very bothered by the fact that changing that first call 'if 0'
to 'if 1' has any effect on the later call to runscript(). That really
doesn't feel right to me...

Any wisdom will be much appreciated.

Cheers,

f

Aug 2 '07 #1
1 2239
Fernando Perez wrote:
I'm finding the following behavior truly puzzling, but before I post a bug
report on the site, I'd rather be corrected if I'm just missing somethin
obvious.

Consider the following trivial script:

from math import sin, pi
wav = lambda k,x: sin(2*pi*k*x)
print wav(1,0.25)
The above runs just fine from a prompt, or even interactively via
execfile(). Now, consider calling it by using this instead:

#!/usr/bin/env python
def runscript(fname):
"""Run a file by calling execfile()."""
execfile(fname)
runscript('execfilebugscript.py')
If I run the above, calling the first script 'execfilebugscript.py' and
the second 'execfilebug.py', I get this:
NameError: global name 'sin' is not defined
I'm really, really puzzled by this. From reading the execfile() docs, I
had the hunch to change the call to:

execfile(fname,{})

and now the problem disappears, so I can keep on working.

If you execfile() a script names not known in the context of a function are
looked up in the global namespace, but assignments set names in the local
namespace.

Consider execfile(filename) for a file

x = 42
def f():
print x
f()

x and f are put into the local namespace, but x is not local to the function
f and therefore looked up in f's globals.

Now if you call execfile() in the global namespace of the client script the
global and local namespace are identical
>>globals() is locals()
True

so x although put into the local namespace will still be found when looked
up in the global namespace. That is the same situation as in your
workaround execfile(filename, {}).

This however is not the case if you call execfile() inside a function. Here
global and local namespace differ.

In your example, when you put another execfile() into the global namespace
of the client script the sin() imported there is the only one that your
wav() function sees. You can verify that by putting

def sin(phi): return "I'm not math.sin()"

instead of

if 1: ....

into execfilebug.py.

Can the current behaviour of execfile() be changed into a more intuitive
one? Not with only two namespaces. You'd probably need something similar to
closures, and I don't think the necessary work would be worth the effort.

Peter

Aug 3 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Jonathan | last post by:
I'm puzzled by Python's behavior when binding local variables which are introduced within exec() or execfile() statements. First, consider this simple Python program: # main.py def f() : x = 1...
2
by: Enrique | last post by:
Hello all! I've a little and no important question: Suppose 2 scripts ##ex.py### a=execfile('scr.py') print "return value: ", a ##scr.py### print "i'm scr.py"
1
by: Bo Jacobsen | last post by:
I have a number of files compiled to bytecode using py_compile.compile(). The .pyc files can be invoked by python directly ($python file.pyc), but "loading" them by execfile just throws an...
3
by: v.vayer | last post by:
I need to execfile() from a function in order to set value for a global variable from inside the executed file. I know there are "globals" and "locals" optional arguments for execfile, but I just...
8
by: R. Bernstein | last post by:
In doing the extension to the python debugger which I have here: http://sourceforge.net/project/showfiles.php?group_id=61395&package_id=175827 I came across one little thing that it would be nice...
2
by: Alex Popescu | last post by:
Hi all! not be present in Py3k. So, I am wondering what will be its replacement? Considering that most probably Py3k will keep eval and exec, this will still be possible (indeed requiring manual...
5
by: George Sakkis | last post by:
I maintain a few configuration files in Python syntax (mainly nested dicts of ints and strings) and use execfile() to read them back to Python. This has been working great; it combines the...
1
by: moijes12 | last post by:
Hi i have 3 python files and i want to execute the files sequentially using the execfile command.Hence ,i have written the following program fileList = for fileName in fileList :...
4
by: TP | last post by:
Hello, I have a script that uses the "optparse" package to parse the command line. For example: $ script.py --help # displays help about script.py Is this possible to call such a script...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.