[Tutor] getattr()

Huy Ton That huyslogic at gmail.com
Wed Aug 4 21:30:56 CEST 2010


*You can do like below Pete. Where globals has a reference to all
functions in this space.*

def output(data, format="text"):

    output_function = getattr(globals()['FUNCTION'], "output_%s" %
format, statsout.output_text)
    return output_function(data)


On Wed, Aug 4, 2010 at 3:18 PM, Pete <pkoek11 at xs4all.nl> wrote:

> Hey Huy,
>
> thanks. But what is the first parameter in this case? (Note there is
> nothing here I'm trying to accomplish except understand).
>
> In the original example, 'statsout' is the name of the module. In this case
> there is no module so why can you substitute 'output_text'?
>
> thanks,
>
> Pete
>
> On 2010-08-04, at 3:09 PM, Huy Ton That wrote:
>
> If it is in the same code, and the namespace isn't a module or another
> class you could do this:
>
> def output_text(data):
>     return_value = "This is text: " + data
>     return return_value
>
> def output(data, format="text"):
>     output_function = getattr(output_text, "output_%s" % format,
> output_text)
>     return output_function(data)
>
> -HTH
>
> Huy
>
> On Wed, Aug 4, 2010 at 1:23 PM, Pete <pkoek11 at xs4all.nl> wrote:
>
>> 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
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100804/249f94b5/attachment-0001.html>


More information about the Tutor mailing list