473,403 Members | 2,284 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,403 software developers and data experts.

exec src in {}, {} strangeness

hi there,

I have trouble running some python code with 'exec':

t.py contains:
class Foo: pass
class Bar:
f = Foo

From a python shell I do:
f = ''.join(open('t.py').readlines())
exec f in {}, {}

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 2, in ?
File "<string>", line 3, in Bar
NameError: name 'Foo' is not defined
However, when I use the current global and local scope, i.e.
simply 'exec f', everything works fine. What am I missing ?

Thanks,
Stefan
Jul 18 '05 #1
8 1300
Hi !
Try :

exec f in globals(),locals()
or
exec(f,globals(),locals())
or
exec f in globals(),globals()
or
exec(f,globals(),globals())

@-salutations

Michel Claveau
Jul 18 '05 #2
Do Re Mi chel La Si Do wrote:
Hi !
Try :

exec f in globals(),locals()
or
exec(f,globals(),locals())
or
exec f in globals(),globals()
or
exec(f,globals(),globals())


Indeed, using 'globals()' and 'locals()' works. However,
both report the same underlaying object, which is a bit
confusing. (Under what circumstances does 'locals()' return
not the same object as 'globals()' ?)

The problem appears to be that

exec f in a, b

where a and b are distinct dictionaries, does not look up
symbols in 'a' when in local scope.
I filed a bug report (#1167300).

Regards,
Stefan
Jul 18 '05 #3
Stefan Seefeld wrote:
Indeed, using 'globals()' and 'locals()' works. However,
both report the same underlaying object, which is a bit
confusing. (Under what circumstances does 'locals()' return
not the same object as 'globals()' ?)


When you aren't at the interactive prompt... there are
no "locals" there, so locals() just maps through to globals().
(Probably this applies to all code at the module level,
as oppsed to code inside any callable, but I haven't
verified... you can easily enough.)

Does this information invalidate your bug report?

-Peter
Jul 18 '05 #4
Peter Hansen wrote:
Stefan Seefeld wrote:
Indeed, using 'globals()' and 'locals()' works. However,
both report the same underlaying object, which is a bit
confusing. (Under what circumstances does 'locals()' return
not the same object as 'globals()' ?)

When you aren't at the interactive prompt... there are
no "locals" there, so locals() just maps through to globals().
(Probably this applies to all code at the module level,
as oppsed to code inside any callable, but I haven't
verified... you can easily enough.)

Does this information invalidate your bug report?


No, but that's possibly only because I don't (yet) understand
the implications of what you are saying.

Is there anything wrong with 'exec source in a, b' where
a and b are distinc originally empty dictionaries ? Again,
my test code was

class Foo: pass
class Bar:
foo = Foo

and it appears as if 'Foo' was added to 'a', but when evaluating
'foo = Foo' the interpreter only looked in 'b', not 'a'.

Thanks,
Stefan
Jul 18 '05 #5
Stefan Seefeld <se*****@sympatico.ca> writes:
Is there anything wrong with 'exec source in a, b' where
a and b are distinc originally empty dictionaries ? Again,
my test code was

class Foo: pass
class Bar:
foo = Foo

and it appears as if 'Foo' was added to 'a', but when evaluating
'foo = Foo' the interpreter only looked in 'b', not 'a'.


No, it's the other way round. Foo is added in b since bindings are done
in the local scope. Your case is a bit more complicated, though.
Here's what I think happens:

class Foo is bound in b, the locals dictionary, so there is no reference
to Foo in the globals dictionary. The body of class B is executed with
it's own new locals dictionary. That locals dictionary will effectively
be turned into Bar.__dict__ when the class object is created.

When "foo = Foo" is executed, Foo is first looked up in that new locals
dictionary. That fails, so it's also looked up in the globals
dictionary a. That fails as well because Foo was bound in b. The final
lookup in the builtins also fails, and thus you get an exception.
Bernhard

--
Intevation GmbH http://intevation.de/
Skencil http://skencil.org/
Thuban http://thuban.intevation.org/
Jul 18 '05 #6
Bernhard Herzog wrote:
Stefan Seefeld <se*****@sympatico.ca> writes:

Is there anything wrong with 'exec source in a, b' where
a and b are distinc originally empty dictionaries ? Again,
my test code was

class Foo: pass
class Bar:
foo = Foo

and it appears as if 'Foo' was added to 'a', but when evaluating
'foo = Foo' the interpreter only looked in 'b', not 'a'.

No, it's the other way round. Foo is added in b since bindings are done
in the local scope. Your case is a bit more complicated, though.
Here's what I think happens:

class Foo is bound in b, the locals dictionary, so there is no reference
to Foo in the globals dictionary. The body of class B is executed with
it's own new locals dictionary. That locals dictionary will effectively
be turned into Bar.__dict__ when the class object is created.

When "foo = Foo" is executed, Foo is first looked up in that new locals
dictionary. That fails, so it's also looked up in the globals
dictionary a. That fails as well because Foo was bound in b. The final
lookup in the builtins also fails, and thus you get an exception.


Thanks for the explanation ! I'm still unable to make a conclusion:
What is wrong ? Am I doing something stupid (I did try various things
such as inserting __builtin__ into the dictionary, etc.) ?
Or is that really a bug ?

Thanks,
Stefan
Jul 18 '05 #7
Stefan Seefeld wrote:
Bernhard Herzog wrote:
When "foo = Foo" is executed, Foo is first looked up in that new locals
dictionary. That fails, so it's also looked up in the globals
dictionary a. That fails as well because Foo was bound in b. The final
lookup in the builtins also fails, and thus you get an exception.

Yes, from the experiment I just did, that does seem to
be what is happening.
Thanks for the explanation ! I'm still unable to make a conclusion:
What is wrong ? Am I doing something stupid...? Or is that really a bug?


It seems to be a hangover from the old two-scope system
where local scopes didn't nest. It probably qualifies as
a bug, since it differs from the modern behaviour of
a class definition inside the local scope of a function.

However, if your intention is to define the classes in
the global dict then yes, you are doing something wrong --
you should be passing the same dictionary for both scopes:

g = {}
exec stuff_to_define in g, g
# definitions are now in g

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
Jul 18 '05 #8
As Greg pointed..

g = {}
exec open('t.py').read() in g, g

is what you want.

But you can write it also this way:
exec open('t.py').read() in {}

because if you specify only globals, the same
dictionary is also used for locals. (locals() is
used as a default only if you don't specify globals)

OR

explicitly move class Foo to globals

t.py contains:
globals Foo
class Foo: pass
class Bar:
f = Foo

(Should work. I haven't tried it, though)

BranoZ

Jul 18 '05 #9

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

Similar topics

1
by: Andr? Roberge | last post by:
I have the following two files: #--testexec.py-- def exec_code(co): try: exec co except: print "error" #-- test.py--
0
by: Jan | last post by:
I store sql-commands in a database table. In the first step I get the sql command out of the database table with embedded sql. In the second step I try to execute the command, which i got from the...
2
by: Robert M. Gary | last post by:
I'm using JRE 1.5 on Solaris Japanese (Sparc). The JVM claims its default character set is EUC-JP I'm seeing two strange things when using Japanese character sets... 1) If I write a program that...
17
by: comp.lang.tcl | last post by:
The TCL command I am using will do a command-line action on a PHP script: set cannotRunPHP I have to do it this way as both the TCL script and the PHP script run as CLI. However, "info.php"...
5
by: TPJ | last post by:
I have the following code: ----------------------------------- def f(): def g(): a = 'a' # marked line 1 exec 'a = "b"' in globals(), locals() print "g: a =", a
4
by: Michael | last post by:
Hi, I'm having difficulty finding any previous discussion on this -- I keep finding people either having problems calling os.exec(lepev), or with using python's exec statement. Neither of...
21
by: comp.lang.tcl | last post by:
set php {<? print_r("Hello World"); ?>} puts $php; # PRINTS OUT <? print_r("Hello World"); ?> puts When I try this within TCL I get the following error:
2
by: xml0x1a | last post by:
How do I use exec? Python 2.4.3 ---- from math import * G = 1 def d(): L = 1 exec "def f(x): return L + log(G) " in globals(), locals() f(1)
26
by: warth33 | last post by:
Hello I have a php site. Some page needs to call an external program. The programs are home made c# applications. It uses to work without problem. For a while. Maybe it work for some hour....
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.