Lambda alternative?

mousemeat at gmail.com mousemeat at gmail.com
Wed Apr 15 15:47:05 CEST 2009


Hello all,

I really like the lambda function for a particular task i have: I am
writing some simulation software, working with many different
materials. Each material with many different properties, some are
temperature dependent, others aren't, some are defined by a function,
some are a lookup table, some are constant. Here is a simplified
version:

class material(object):
    def __init__(self,density):
        self.density=density

airdensity=lambda T:100000/(287*T)
air=material(airdensity)

steeldensity=lambda T:interp(T,[0,1000],[7856,7813])
steel=material(steeldensity)

rockdensity=lambda T:5000
rock=material(rockdensity)

I really like doing things this way, because i can then define other
properties within the class and i can always use the syntax:
specificgravity_at_273K=stone.specificgravity(273), whether
specificgravity is a function or a parameter. (not sure thats the
right nomenclature, but i think you'll know what i mean.)

But, lambda functions can't be pickled. I would like to pickle my
objects, and i would really like to use parallel python (which
requires pickling).

The best way i can see to do that is to make a new class which
inheirits the 'material' class for each physical material i want to
model, but surely i should be creating instances rather than classes.

Is this going to present some new problems that anyone can forsee? Can
anyone think of a better way to do this?  I keep reading that lambda
functions aren't particularly pythonic and that there are always
alternatives, but they seem very elegant to me.

Thanks for your time,

Warren



More information about the Python-list mailing list