[Tutor] getattr()

Pete pkoek11 at xs4all.nl
Wed Aug 4 19:23:13 CEST 2010


Hi,

I'm trying to understand the syntax for reflection in python. I was wondering about this.

From the example on diveintopython:

   http://diveintopython.org/power_of_introspection/index.html

import statsout

def output(data, format="text"):
    output_function = getattr(statsout, "output_%s" % format, statsout.output_text)
    return output_function(data) 

I was wondering about how to make this work if the function that you are trying to call is not in a module. Is that possible?

Something like this:

def output_text(data):
    return_value = "This is text: " + data
    return return_value

def output(data, format="text"):
    output_function = getattr(*****, "output_%s" % format, statsout.output_text)
    return output_function(data)

What I can't figure out is what to put in place of *****. I've tried globals()['__name__'], in various forms, to no avail.

Any pointers would be appreciated.

thanks,

Pete

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100804/7f358f1c/attachment.html>


More information about the Tutor mailing list