getattr on a function

M

Mr SZ

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>) !

" 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.
 
P

Peter Otten

Mr said:
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
 
J

John Machin

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 ;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top