Forgetting "()" when calling methods

Alex Martelli aleax at aleax.it
Sun Apr 27 09:52:37 CEST 2003


Andrew Bennetts wrote:
   ...
> lack of a better word.  It's usually not any clearer to say
>     
>     if len(myList) == 0:
>         print "I have a list of stuff"

The "== 0" part here is making it to the reverse of what you probably mean.


> than
> 
>     if myList:
>         print "I have a list of stuff"

Absolute agreement here.


> I think the same applies to testing to see if a variable holds a callable,

Not at all.  "if callable(thevariable):" is the one obvious way to check
THAT.  "if thevariable:" is going to have you try to call the number 23,
the string 'loolapalooza', and non-empty dicts and lists.

> just as much as it applies to checking the length of something.  Removing

The two cases are very different.  "if len(myList):" is equivalent to
"if myList:" *for a known given type of myList* -- a container.  In
the callable case, you _don't know_ the type -- and are checking the
VALUE to try and infer the TYPE.  Checking callable(f) is more obvious
and direct -- it clearly and unambiguously shows what you're checking.

> this feature will lead to unnecessarily longer code for minimal benefit.

I dispute the "unnecessarily" and the "minimal".  Tests for "is None"
add clarity (when they're applicable), and tests for callable(f) even
more so.  And giving newbies a little help by diagnosing a very common
newbie error more promptly would help (or at least it might, were it
not for some newbies' insistence that the diagnosis should be performed
by static analysis instead -- it just can't, and thus said insistence
convinces me that this is not worth putting to a PEP -- however, I find
the arguments against it quite unconvincing, except for the "we can't
break this idiom because even though it's inferior it's widely used").


Alex






More information about the Python-list mailing list