473,399 Members | 4,254 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,399 software developers and data experts.

problem with exec and locals()


Hi,

the following code does not work until I ommit the "a=0" statement.
def test():
exec "a=3" in locals()
print a
a=0

test()

print raises:
UnboundLocalError: local variable 'a' referenced before
assignment

Can anybody explain what is going wrong here ?

Greetings, Uwe
Jul 1 '08 #1
4 1324
Mel
rocksportrocker wrote:
>
Hi,

the following code does not work until I ommit the "a=0" statement.
def test():
exec "a=3" in locals()
print a
a=0

test()

print raises:
UnboundLocalError: local variable 'a' referenced before
assignment

Can anybody explain what is going wrong here ?
AFAIK, local variables are implemented rather like __slots__ in new-style
classes. This is a very valuable efficiency measure, but it can cause this
kind of trouble. Without `a=0`, the bytecode compiler makes no slot for a,
and dis.dis shows the following bytecode for test:
>>dis.dis (test)
2 0 LOAD_CONST 1 ('a=3')
3 LOAD_NAME 0 (locals)
6 CALL_FUNCTION 0
9 DUP_TOP
10 EXEC_STMT

3 11 LOAD_NAME 1 (a)
14 PRINT_ITEM
15 PRINT_NEWLINE
16 LOAD_CONST 0 (None)
19 RETURN_VALUE

At address 11, LOAD_NAME 1(a) gets the value that was set by exec.

With a=0, the code is
>>dis.dis(test2)
2 0 LOAD_CONST 1 ('a=4')
3 LOAD_NAME 0 (locals)
6 CALL_FUNCTION 0
9 DUP_TOP
10 EXEC_STMT

3 11 LOAD_FAST 0 (a)
14 PRINT_ITEM
15 PRINT_NEWLINE

4 16 LOAD_CONST 2 (0)
19 STORE_FAST 0 (a)
22 LOAD_CONST 0 (None)
25 RETURN_VALUE

and here, the value of a is found in slot 0 via LOAD_FAST. Slot 0 is used
because a=0 forced a to be a local variable.

Apparently, exec in locals() knows nothing about slots (because locals() is
the only dictionary in the universe where slots would be involved ? --
perhaps not, but close).

Mel.

Jul 1 '08 #2
On 1 Jul., 15:15, Mel <mwil...@the-wire.comwrote:
rocksportrockerwrote:
Hi,
the following code does not work until I ommit the "a=0" statement.
* *def test():
* * * *exec "a=3" in locals()
* * * *print a
* * * *a=0
* * test()
print raises:
* * *UnboundLocalError: local variable 'a' referenced before
assignment
Can anybody explain what is going wrong here ?

AFAIK, local variables are implemented rather like __slots__ in new-style
classes. *This is a very valuable efficiency measure, but it can cause this
kind of trouble. *Without `a=0`, the bytecode compiler makes no slot for a,
and dis.dis shows the following bytecode for test:>>dis.dis (test)

* 2 * * * * * 0 LOAD_CONST * * * * * * * 1 ('a=3')
* * * * * * * 3 LOAD_NAME * * * * * * * *0 (locals)
* * * * * * * 6 CALL_FUNCTION * * * * * *0
* * * * * * * 9 DUP_TOP
* * * * * * *10 EXEC_STMT

* 3 * * * * *11 LOAD_NAME * * * * * * * *1 (a)
* * * * * * *14 PRINT_ITEM
* * * * * * *15 PRINT_NEWLINE
* * * * * * *16 LOAD_CONST * * * * * * * 0 (None)
* * * * * * *19 RETURN_VALUE

At address 11, LOAD_NAME 1(a) gets the value that was set by exec.

With a=0, the code is>>dis.dis(test2)

* 2 * * * * * 0 LOAD_CONST * * * * * * * 1 ('a=4')
* * * * * * * 3 LOAD_NAME * * * * * * * *0 (locals)
* * * * * * * 6 CALL_FUNCTION * * * * * *0
* * * * * * * 9 DUP_TOP
* * * * * * *10 EXEC_STMT

* 3 * * * * *11 LOAD_FAST * * * * * * * *0 (a)
* * * * * * *14 PRINT_ITEM
* * * * * * *15 PRINT_NEWLINE

* 4 * * * * *16 LOAD_CONST * * * * * * * 2 (0)
* * * * * * *19 STORE_FAST * * * * * * * 0 (a)
* * * * * * *22 LOAD_CONST * * * * * * * 0 (None)
* * * * * * *25 RETURN_VALUE

and here, the value of a is found in slot 0 via LOAD_FAST. *Slot 0 is used
because a=0 forced a to be a local variable.

Apparently, exec in locals() knows nothing about slots (because locals() is
the only dictionary in the universe where slots would be involved ? --
perhaps not, but close).

* * * * Mel.
Thanks for your answer. I wonder if this is a bug, or did I miss
something
in the docs ???

Greetings, Uwe
Jul 11 '08 #3
Uwe Schmitt wrote:
>Apparently, exec in locals() knows nothing about slots (because locals()
is the only dictionary in the universe where slots would be involved ? --
perhaps not, but close).

Mel.

Thanks for your answer. I wonder if this is a bug, or did I miss
something in the docs ???
Hm, the documentation has an explicit warning:

http://docs.python.org/lib/built-in-funcs.html#l2h-47

"""
locals( )
Update and return a dictionary representing the current local symbol table.
Warning: The contents of this dictionary should not be modified; changes
may not affect the values of local variables used by the interpreter.
"""

By the way, the local namespace is affected if you don't provide it
explicitly:
>>def f():
.... exec "a=42"
.... print a
.... a = "whatever"
....
>>f()
42

Peter

Jul 11 '08 #4
En Fri, 11 Jul 2008 03:51:39 -0300, Uwe Schmitt
<ro*************@googlemail.comescribi�:
On 1 Jul., 15:15, Mel <mwil...@the-wire.comwrote:
>rocksportrockerwrote:
the following code does not work until I ommit the "a=0" statement.
Â* Â*def test():
Â* Â* Â* Â*exec "a=3" in locals()
Â* Â* Â* Â*print a
Â* Â* Â* Â*a=0
Â* Â* test()
print raises:
Â* Â* Â*UnboundLocalError: local variable 'a' referenced before
assignment
Can anybody explain what is going wrong here ?

AFAIK, local variables are implemented rather like __slots__ in
new-style
classes. Â*This is a very valuable efficiency measure, but it can cause
this
kind of trouble. Â*Without `a=0`, the bytecode compiler makes no slot
for a,

Thanks for your answer. I wonder if this is a bug, or did I miss
something
in the docs ???
Read the warnings in the docs for the locals() builtin function:
http://docs.python.org/lib/built-in-funcs.html#l2h-47
and the execfile function:
http://docs.python.org/lib/built-in-funcs.html#l2h-26

--
Gabriel Genellina

Jul 11 '08 #5

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

Similar topics

5
by: Nick Jacobson | last post by:
This works fine: x = 1 def execfunc(): print x execfunc() So why doesn't this? s = \
2
by: tedsuzman | last post by:
----- def f(): ret = 2 exec "ret += 10" return ret print f() ----- The above prints '12', as expected. However,
8
by: Filip Dreger | last post by:
Each function has a func_code property that is suposed to contain the pure bytecode of the function. All the context (including reference to relevant namespaces) is stored in different fields of...
10
by: Antoon Pardon | last post by:
I have the following little piece of code: class Cfg:pass #config = Cfg() def assign(): setattr(config, 'Start' , ) def foo(): config = Cfg()
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
3
by: Jens | last post by:
Hi, has anyone an idea why the following code does not work. s = """ def a(n): return n*n
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)
4
by: carl.dhalluin | last post by:
Hello I am completely puzzled why the following exec code does not work: mycode = "import math\ndef f(y):\n print math.floor(y)\nf(3.14)" def execute(): exec mycode execute()
0
by: Stef Mientki | last post by:
Terry Reedy wrote: The locals of the code block where the instance of this class is created. No I think it's indeed handled as function call. I now that, because the globals (and sometimes ??? the...
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
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
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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.