Calling a function dynamically

Paradox JoeyTaj at netzero.com
Sat Jan 10 15:43:30 EST 2004


Thanks to all. The getattr was exactly what I need and the __getitem__
override is a nice touch.


Dave Benjamin <ramen at lackingtalent.com> wrote in message news:<slrnbvr5hb.seu.ramen at lackingtalent.com>...
> In article <btk1i4$ca4$02$1 at news.t-online.com>, Peter Otten wrote:
> > Paradox wrote:
> > 
> >> I would like to call a function whose name I supply at runtime.
> >> [snip]
> > 
> > Here's a way to abuse the [] operator (implemented by __getitem__()) to
> > dynamically select a method...
> > 
> >>>> t["run"]("alpha", "beta", "gamma")
> > run('alpha', 'beta', 'gamma')
> 
> I wouldn't necessarily consider this abuse. This behavior (where
> square-bracket- and dot-syntax are functionally equivalent) is the normal
> behavior of JavaScript, and it makes dynamic lookup of method names a snap.
> Python is more flexible in giving you the option to have separate namespaces
> for items and attributes, but if it makes more sense for an object to merge
> the two, I see nothing wrong with it.



More information about the Python-list mailing list