Parameterized Functions without Classes
Christian Tismer
tismer at stackless.com
Fri Jun 25 12:54:03 EDT 2004
Hi Pythonistas,
just as a small comment on the side-effects of the
rather new concept of local functions with access to
their scope:
This concept can be used to avoid having extra
classes just for keeping some read-only state.
Since this feature is not so obvious in the first
place, I thought to share the obervation.
In the ancient times, I saw myself writing classes
to parameterize functions, like this:
class Converter:
def __init__(self, scale):
self.scale = scale
def __call__(self, arg):
return self.scale * arg
inch_to_cm = Converter(2.54)
cm_to_inch = Converter(1 / 2.54)
...
>>> inch_to_cm(20)
50.799999999999997
>>> cm_to_inch(20)
7.8740157480314954
>>>
This can be easily done without an extra class, just by
local variables which access the outer scope:
def _converter(scale):
def convert(arg):
return scale * arg
return convert
inch_to_cm = _converter(2.54)
cm_to_inch = _converter(1 / 2.54)
>>> inch_to_cm(20)
50.799999999999997
>>> cm_to_inch(20)
7.8740157480314954
>>>
This trick (and I don't consider it a trick) works for
all cases, where you don't need write access to an instance
variable, but read access, only.
It is a very clean way to parameterize functions, and it
is very effective since there is no attribute lookup
necessary.
cheers - chris
--
Christian Tismer :^) <mailto:tismer at stackless.com>
Mission Impossible 5oftware : Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a : *Starship* http://starship.python.net/
14109 Berlin : PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34 home +49 30 802 86 56 mobile +49 173 24 18 776
PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04
whom do you want to sponsor today? http://www.stackless.com/
More information about the Python-list
mailing list