Forgetting "()" when calling methods

Andrew Bennetts andrew-pythonlist at puzzling.org
Sat Apr 26 12:36:24 CEST 2003


On Sat, Apr 26, 2003 at 10:05:42AM +0000, Alex Martelli wrote:
[..snip..]
> I don't know what to DO about it, but some minor tweaks might help.
> For example, I cannot think of any code I've ever written that would
> break if methods (and functions) spouted a __nonzero__ special method
> (or, of course, the C-coded equivalent thereof) raising an exception
> with a clear error message -- this would at least provide prompt

I can!  I'm sure Twisted, and probably other places, use this idiom:

    # Call a handler if one is defined
    func = getattr(self, 'handler_' + name', None)
    if func:
        func(...)

This idiom could be easily adapted to use "if func is not None", but it's
not clear that that's a better way to express it.  Anyway, my point is that
making function's __nonzero__ raise an exception will certainly break
existing code!

The same could probably be said of, e.g. setting class's and type's
__nonzero__ to raise an exception, to avoid "instance = MyClass" bugs too.
I think this would also break things.  "if foo:" is just too commonly relied
upon to mean "is 'foo' *something*, or just an empty placeholder?" in
Python, and so making anything's __nonzero__ raise an exception is probably
a bad idea.

-Andrew.






More information about the Python-list mailing list