[Tutor] exec('a=1') in functions
Peter Otten
__peter__ at web.de
Wed Aug 18 03:11:01 EDT 2021
On 17/08/2021 18:37, Jan Kenin wrote:
> Hello,
>
> in python 2.7 the following code works:
> >>> def f( b ):
> ... exec( 'a=%s'%b )
> ... print 'a=', a
> ...
> >>> f( 1 )
> a= 1
>
> in python3.6 this works in the interpreter:
> >>> b=1
> >>> exec('a=%s'%b)
> >>> a
> 1
>
> but not in a function:
> >>> def f( b ):
> ... exec( 'a=%s'%b )
> ... print( 'a=', a )
> ...
> >>> f( 1 )
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<stdin>", line 3, in f
> NameError: name 'a' is not defined
>
> How can I get the latter working?
You can't. In Python 2 the exec statement modified the byte code, with
sometimes surprising consequences.
In Python 3 exec() is an ordinary function; you have to copy data from
its namespace into the function explicitly. Example:
>>> def f(b):
ns = dict(b=b)
exec("a = b", ns)
a = ns["a"]
print(f"{a=}")
>>> f(42)
a=42
Less magic, but much cleaner ;)
More information about the Tutor
mailing list