[Tutor] Import module function using variable
Alan Gauld
alan.gauld at yahoo.co.uk
Wed Jun 13 03:37:12 EDT 2018
On 13/06/18 02:52, Slater, Joseph C. wrote:
> I am trying to import a function in a module by variable name.
I'd suggest getattr():
>>> import sys
>>> xt = getattr(sys,exit)
>>> xt()
Alternatively, if its a fixed set of options
(and it sound as if it is) set up a dictionary:
funcs = {'exit': sys.exit, size: sys.getsizeof)
xt = funcs('exit')
xt()
Which has the advantage of providing a menu
of friendly function names to the user:
for func in funcs:
print(func)
fn = input('choose a function from the list above')
And allows you to validate the selection
if fn in funcs.keys():
f = funcs[fn]
else: print(...)
HTH
--
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