[Tutor] getattr()

Huy Ton That huyslogic at gmail.com
Wed Aug 4 21:44:22 CEST 2010


Oh, that's right, I should have tried to example in the interpreter instead
of in my head:P

Say Bob,

Is that the preferred method over something like:

>>> import __main__ as main

On Wed, Aug 4, 2010 at 3:32 PM, bob gailer <bgailer at gmail.com> wrote:

>  On 8/4/2010 1:23 PM, Pete 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.
>
>
> Everything in Python is in a module. I suspect you mean not in an imported
> module, e.g. in the main module. Whose __name__ is '__main__'. A reference
> to the main module can be found:
>
> import sys
> main = sys.modules['__main__']
>
>  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.
>
>
> Replace those stars with main as derived above.
>
> globals()['output_text'] will also give you a reference to the function.
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
>
> _______________________________________________
> 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/5d02cfbe/attachment.html>


More information about the Tutor mailing list