[Tutor] exec('a=1') in functions
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Aug 18 05:09:54 EDT 2021
On 17/08/2021 17:37, Jan Kenin wrote:
> in python3.6 this works in the interpreter:
> >>> b=1
> >>> exec('a=%s'%b)
> >>> a
> 1
>
> but not in a function:
> How can I get the latter working?
Peter has already explained the changes in v3.
But I assume you fully understand the dangers
of using exec() in real code? It is an advanced
technique that should only be used as a last
resort. Certainly not for the trivial example
shown, but even in more complex cases there
is nearly always a way to code it directly
rather than using exec().
I apologize if this is patronising but the
tutor list is read by many beginners and
they may not realize what dangerous tools
exec/eval etc are. So the warning is almost
obligatory whenever they get mentioned.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list