Python

More on What is "pythonic"


21st of May 2010

About 5 years ago Martijn Faasen wrote the wonderful blog article What is Pythonic. One thing that I feel is extremely Pythonic is to not compare certain thing to other things when Python has built-in understanding of what false or true means.

Having reviewed/read a lot of beginner code or senior code but of people coming from lower-level languages I often see this:

 if variable == False:
 ...
 if variable == 0:
 ...
 if variable == None:
 ...
 if len(variable) == 0:
 ...
 if variable == []:
 ...
 if variable == {}:
 ...
 if ORM.filter(user=variable).count == 0:
 ...
 if not bool(variable):
 ... 

To be Pythonic is to understand that Python evaluates all of these to false. All built in types have a perfectly sensible boolean operator which is automatically used in an if statement or an embedded if statement in a list comprehension. Keep it clean a pure just like this to check for true:

 if not variable:
 ...
 if not ORM.filter(user=variable):
 ...

And if you have your custom class such as the example just above with the pseudo "ORM" it's easy to extend it by writing your own custom __bool__ like this:

 class MyCustomType(somebuiltintype):
    ...
    def __bool__(self):
        return self.somedate and self.somecondition

By playing along with Python just the way Guido indented it you can abstract yourself from being overly dependent of types. By doing the shorthand notation a variable that is otherwise a list can be None if it's not set and your code will continue to work.

All the above might not be true for more explicit lower-level languages like C++ but it sure is Pythonic in Python and that's a good thing.



Comment

Show all 6 comments
 

Commenting is currently disabled in Mobile version