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>) !
" life isn't heavy enough,it flies away and floats far above action"
Enjoy a safer web experience. Upgrade to the new Internet Explorer 8 optimised for Yahoo!7. Get it now.
> 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>) !
From within the module:
encryption = ...
f = globals()["func" + encryption]
f(...)
In other modules, assuming the module containing the function is
called 'module':
import module
encryption = ...
f = getattr(module, "func" + encryption)
f(...)
Peter
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 ;-)
funcs = {'none':func, 'SSL':funcSSL, 'TLS':funcTLS}
...
cryptfunc = funcs[ <expression yielding 'none', 'SSL', or 'TLS'> ]
> ...
>
> 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>) !
>
> " life isn't heavy enough,it flies away and floats far above action"
>
>
> Enjoy a safer web experience. Upgrade to the new Internet Explorer 8 optimised for Yahoo!7. Get it now.