sum() requires number, not simply __add__
steve+comp.lang.python at pearwood.info
Thu Feb 23 18:33:39 EST 2012
On Fri, 24 Feb 2012 08:53:49 +1100, Chris Angelico wrote:
> On Fri, Feb 24, 2012 at 8:41 AM, Arnaud Delobelle <arnodel at gmail.com>
>> _sentinel = object()
>> def sum(iterable, start=_sentinel):
>> if start is _sentinel:
>> del _sentinel
> Somewhat off-topic: Doesn't the if statement there do a lookup for a
> global, which would mean that 'del _sentinel' will cause it to fail? Or
> have I missed something here?
Yes, deleting _sentinel will cause the custom sum to fail, and yes, you
have missed something.
If the caller wants to mess with your library and break it, they have
many, many ways to do so apart from deleting your private variables.
_sentinel = "something else"
sum.__defaults__ = (42,) # mess with the function defaults
sum.__code__ = (lambda a, b=None: 100).__code__ # and with func internals
sum = None # change your custom sum to something else
del sum # or just delete it completely
len = 42 # shadow a built-in
import builtins; del builtins.range # really screw with you
If your application stops working after you carelessly mess with
components your application relies on, the right answer is usually:
"Don't do that then."
Python doesn't try to prevent people from shooting themselves in the foot.
More information about the Python-list