Forgetting "()" when calling methods

Gerhard Häring gh at ghaering.de
Fri Apr 25 18:24:00 EDT 2003


Frantisek Fuka wrote:
> 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...
> 
> If I understand it correctly, the if statement in this case tests if 
> pointer to hasParent method is non-zero, which is of course always True 
> so no error is reported and "do something..." always gets executed, so 
> the application behaves in quite different way than I expected.

Yup. We prefer to talk about references instead of pointers, though.

> You can say to me "Don't forget to always include the parenteses"

Ok, "Don't forget to always include the parentheses" :-)

> but 
> I'm still curious if this cannot be somehow configured, so that I get 
> error when I try to just access the method pointer (".isGreen") instead 
> of calling the method (".isGreen()").

Ok, you asked for it ;-) Here's something special-cased for not 
forgetting the parentheses if the function is a boolean one and is used 
in an if-statement:

 >>> class DontForgetTheParens:
...   def __init__(self, callable):
...     self.callable = callable
...   def __nonzero__(self):
...     raise SyntaxError, "Don't forget the parentheses!"
...   def __call__(self, *args, **kwargs):
...     return self.callable(*args, **kwargs)
...
 >>> def foo(): return 5
...
 >>> foo = DontForgetTheParens(foo)
 >>> if foo(): print "5"
...
 >>> if foo: print "5"
...
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 5, in __nonzero__
SyntaxError: Don't forget the parentheses!
 >>>

Your homework for the weekend is to understand how this works ;-)

I hope it's clear that this falls into the "neat but useless" category.

If you want something more useful, I'd recommend you have a look at 
PyChecker. It should probably warn you about such programming mistakes.

-- Gerhard





More information about the Python-list mailing list