Why are functions atomic?

Carsten Haese carsten at uniqsys.com
Tue May 1 21:32:55 EDT 2007


On Tue, 2007-05-01 at 17:28 -0700, Michael wrote:
> A bit more info, but still no clear picture about why functions are
> mutable but have immutable copy symantics.  There are arguments why
> functions should be immutable, but the decision was to make user-
> defined functions mutable.  My question is still: why the present
> ummutable copy symantics?

One could make a case that this is a bug, a leftover from when functions
were mostly immutable. However, one can also make a case that correcting
this bug is not worth the effort. Your use case appears to be that you
want to make multiple copies of the same function, and those copies
should be almost, but not quite, the same.

The Pythonic solution is to produce the copies by a factory function
along these lines:

>>> def powerfactory(exponent):
...    def inner(x):
...       return x**exponent
...    return inner
... 
>>> square = powerfactory(2)
>>> cube = powerfactory(3)
>>> square(2)
4
>>> square(3)
9
>>> cube(2)
8
>>> cube(3)
27

This approach makes copying functions unnecessary, and as you have
pointed out yourself, if you find yourself needing to make a copy of an
existing function you can work around the unexpected copy semantics with
new.function.

-Carsten





More information about the Python-list mailing list