Forgetting "()" when calling methods
Andrew Bennetts
andrew-pythonlist at puzzling.org
Sun Apr 27 01:47:06 EDT 2003
On Sat, Apr 26, 2003 at 10:15:03PM -0700, Jeremy Fincher wrote:
> Frantisek Fuka <fuka at fuxoft.cz> wrote in message news:<b8cadp$1fj9$1 at ns.felk.cvut.cz>...
> > When I try to call methods, I sometimes forget to include the
> > parentheses. Instead of:
> >
> > if object.isGreen():
> > do something...
> >
> > i sometimes write:
> >
> > if object.isGreen:
> > do something...
>
> Perhaps the answer is to remove the __nonzero__ method on
> functions/methods. Logically, what purpose does it serve?
As I posted earlier in this thread, it allows this idiom:
# Call the handler for this, if one exists
handler = getattr(self, 'handler_' + name, None)
if handler:
handler(data)
I can see similar uses for another type of callable: classes. E.g.:
class XylophonePacket(Packet):
...
class AccordionPacket(Packet):
...
packetTypes = {
'XY': XylophonePacket,
'AC': AccordionPacket,
'PI': None # Ignore pianos
}
class MusicalNetworkProtocol(Protocol):
def dataReceived(self, data):
try:
packetType = packetTypes[data[:2]]
except KeyError:
raise BadPacketType, data[:2]
if packetType:
packet = packetType(data)
...
That's a contrived example off the top of my head -- but I have used code
very similar to that in the past.
There are certainly alternate ways to do these things that don't rely on
functions, methods and classes having a __nonzero__ (e.g. testing against
"is not None", or using a "lambda x: None" default argument), but there is
certainly existing code that relies upon this behaviour, so I think this
can't be changed until Python 3000.
Even for Python 3000, I'm not sure it's a good idea. It's currently
commonplace to simply say "if foo" to check if something isn't "empty", for
lack of a better word. It's usually not any clearer to say
if len(myList) == 0:
print "I have a list of stuff"
than
if myList:
print "I have a list of stuff"
I think the same applies to testing to see if a variable holds a callable,
just as much as it applies to checking the length of something. Removing
this feature will lead to unnecessarily longer code for minimal benefit.
-Andrew.
More information about the Python-list
mailing list