A question on python performance.

Paul Hankin paul.hankin at gmail.com
Wed Sep 26 19:22:49 EDT 2007


On Sep 26, 7:26 pm, "Joe Goldthwaite" <j... at goldthwaites.com> wrote:
> The code gets kind of wordy so I started trying to figure out how to call
> them dynamically since the param type is the same as the method the
> retrieves it.  I came up with this;
>
> def getValue(trend, param, per):
>    return trend.__class__.__dict__[param](trend, per)
>
> That worked but it seems like the above line would have to do lots more
> object look ups at runtime so I didn't think it would be very efficient.  I
> thought maybe I could add a caller method to the trend class and I came up
> with this;
>
> class trend:
>    ...
>    ...
>    ...
>    def caller(self, param, *args):
>       return self.__class__.__dict__[param](self, *args)
>
> This simplified the getValue function to this;
>
> def getValue(trend, param, per):
>         return trend.caller(param, per)

You're calling a function (getValue) that just calls a method of trend
(caller), that just calls another method of trend (Ptd or Qtd or ...).
You can skip all these steps, and just call the method yourself: the
code that calls getValue(trend, param, per) replace with
trend.<something>(per) if you're calling getValue with a static value
for param, or getattr(trend, param)(per) if param is dynamic.

--
Paul Hankin




More information about the Python-list mailing list