A question on python performance.

Erik Jones erik at myemma.com
Wed Sep 26 15:54:35 EDT 2007


On Sep 26, 2007, at 1:26 PM, Joe Goldthwaite wrote:

> Hi everyone,
>
> I'm a developer who's been using python for a couple of years.  I  
> wrote a
> fairly large application using it but I was learning the language  
> at the
> same time so it most of the code kind of sucks.
>
> I've learned a lot since then and I've been going through my code  
> trying to
> organize it better and make better use of Python's features.  I'm  
> still  not
> an expert by any definition but I'm slowly getting better.
>
> I've been working on a trend class that takes twelve monthly  
> numbers and
> returns a period to date, quarter to date, year to date and  
> quarterly year
> to date numbers for a specific period. This worked but I ended up  
> with a lot
> of code like this;
>
> def getValue(trend, param, per):
>    if param == 'Ptd':
>      return trend.Ptd(per)
>    elif param == 'Qtd':
>       return trend.Qtd(per)
>    elif param == 'Ytd':
>       return trend.Ytd(per)
>    elif param == 'YtdQ':
>       return trend.YtdQ(per)
>
> 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)


What you're describing is a case of mulitple dispatch.  See http:// 
www.artima.com/weblogs/viewpost.jsp?thread=101605 for a short  
description and (as short) example by Guido.  You can probably fill  
that out and adapt it to your needs.  Alternatively, you could look  
into the multimethods module in the Gnosis Utilities package: http:// 
pypi.python.org/pypi/Gnosis_Utils/1.2.1-a


Erik Jones

Software Developer | Emma®
erik at myemma.com
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com





More information about the Python-list mailing list