[Tutor] Assign exec() value to a variable
Alan Gauld
alan.gauld at btinternet.com
Fri Oct 11 05:36:04 EDT 2019
On 10/10/2019 22:26, Eggo why wrote:
> Hi all,
> How can I assign result from exec() into a variable.
You can't, exec() doesn't return anything it just executes
the code. But that's not a problem because you should almost
never use exec(). It is a security nightmare, impossible to
debug, and there are nearly always better ways to achieve
what you want safely (or at least more safely!).
> import config
>
> sid='configdb'
> SID = ("config.%s()" % sid)
> print('--params: ',SID)
> params = exec(SID)
So what you really want is to execute config.configdb()
but, presumably, want the function to be assigned dynamically
rather than statically. And you want the return value.
The simplest solution is to use eval rather than exec()
since eval returns the result. But eval has many of the
same problems as exec()
I see Mats has already pointed you at getattr()
Another approach is to create a dispatch table (or dict)
of all the config functions that you want to execute and
then translate your dynamic input into one of those and
call it indirectly via the table. This is one of the
safest methods, since you can only call the things you
know are valid, and quite fast.
dispatch = {'friendly name': config.func,
'another name': config.func2
}
func_name = get_func() # get the function name from wherever
try: param = dispatch[func_name]()
except KeyError: print("No such function")
You could replace the last two lines with
param = dispatch.get(func_name, lambda : print("No such function"))()
But I personally think the try/except is easier to read
and allows more flexibility.
--
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