getattr on a function
John Machin
sjmachin at lexicon.net
Mon Apr 27 13:32:34 EDT 2009
On Apr 28, 2:30 am, Mr SZ <sk8in_zo... at yahoo.com.au> wrote:
> Hi all,
>
> Is it possible to call functions using getattr. I have written a simple script with functions that call either SSL, TLS or plain functionality.
>
> something like:
> def func():
> ...
>
> def funcSSL():
> ...
>
> def funcTLS():
> ...
>
> Now, based on my args I would like to call either one of them. In my case, I can't seem to figure out what my object would be when I call getattr(object, 'func'+<encryption>) !
A function is an attribute of the module that the function is defined
in. If you don't want to hard-code the name of the module,
you can use the fact that the name __name__ is bound to the current
module, and sys.modules provides a mapping from module names to the
actual module objects.
So: getattr(foomodule, 'func' + encr)
or: getattr(sys.modules[__name__], 'func' + encr)
Or, in the same module you could have:
encrfuncdict = {
'SSL': funcSSL,
# etc
}
and your call would be encrfuncdict[encryption](arg1, arg2, ...)
*AND* folk reading your code wouldn't have to write in and ask what
all that getattr() stuff was doing ;-)
More information about the Python-list
mailing list