[Tutor] not operator

Paul McGuire ptmcg at austin.rr.com
Fri Sep 19 11:49:54 CEST 2008


 
>>> the below doesn't work in python
>>> >>> if !(os.access(target_dir, os.F_OK)):
>>> SyntaxError: invalid syntax

What is that '!'? doing there?  A left-handed factorial?  

I'm just kidding, I know that '!' is a common 'not' operator in many other
programming languages.  But this is Python, man!  The not operator is 'not'.

    if not os.access(target_dir, os.F_OK):
    
is perfectly legit Python.

And I concur with Steve Willoughby's note on omitting '== True' and '==
False' - the 'if' and 'while' statements are perfectly aware that their
purpose is to evaluate the boolean-ness of a condition expression.  Not only
is '== True' in 'if blah == True:' redundant and unnecessary clutter*, it
defeats some of Python's language idioms in which strings and containers
(lists, dict, sets, and tuples) have an implicit boolean value indicating
False if they are empty and True if non-empty.  Here is an inefficient way
to empty a list:
    
listvar = range(10)
while listvar:
    print len(listvar)
    listvar.pop()

But change it to:

while listvar == True:

and the loop wont run even once - listvar is not equal to True, and never
will be.

To my mind, '== True' is a crutch for bad naming.  Functions that return a
boolean should be named 'is_blah' or 'is_foo' so that it is clear they are
testing and returning the blahness or fooishness of their object.

For example, let's imagine that we've written a Configuration class that has
a number of properties that, when set independently, may get the class into
an inconsistent state - maybe not the greatest design, but sometimes this
can't be helped.  So we add to our class a validation member function to
return a boolean to indicate if the instance is valid or not.  If we call
the method 'validate', we are tempted to write:
    
if config.validate() == True:
    
because validate, being a transitive verb, tells us we are going to do
something to config, but since 'validate' is not a name that clearly asserts
a truth or falsity, we aren't exactly sure what validate is going to return
for valid vs. invalid configs (I could envision a function named 'validate'
could return a list of validation errors, for example).  A better name here
is 'is_valid', so that the '== True' can just be dropped, and the code reads
clearly as:
    
if config.is_valid():
    
</soapbox>
-- Paul

* yes, I know this phrase is itself multiply redundant - sometimes I just
crack myself up.



More information about the Tutor mailing list