[Tutor] exec('a=1') in functions
Mark Lawrence
breamoreboy at gmail.com
Tue Aug 17 20:52:32 EDT 2021
On 17/08/2021 17: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?
>
> Thanks for all advice!
> Jan
Quite frankly I've no idea, but even if I did know I'd advise you not to
use it. See e.g.
https://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list