Simeon Franklin
Blog :: What is "Un-Pythonic"?
15 December 2011
Tonight's Baypiggies topic is going to be What is Pythonic - Marilyn Davis is doing the presentation. I had a few thoughts but they're all in the opposite direction. I don't feel authoritative enough to define Pythonicness but as an instructor I frequently get to see code written by students new to Python that is obviously un-pythonic, for lack of a better term.
I thought about some recent examples and came up with a coherence to unpythonicness. See if you see the commonality between the following examples of Pythonic code:
Testing for empty values
if x == "":
dostuff()
if len(x) == 0:
dosomethingelse()
How about getter/setter methods
class Stuff(objects):
def __init__(self, num):
self.num = num
def get_num(self):
# Do some other stuff
return self.num
def set_num(self, num):
# Do some other stuff
self.num = num
or filtering a list
newlst = []
for val in lst:
if somecheck(val):
newlst.append(val)
Each of these examples is a pattern (simple or complex) that is directly supported by Python. Builtin datatypes have a boolean sense (a non-empty string is not True or False but it is "truthy"), getters/setters are supplied by the @property decorator and the filter builtin or a list comprehension is a more succinct and specific means of filtering a list.
My unifying principle? Code that does a task manually or explicitly that Python has syntactic or builtin support for is unpythonic. The corollary is that it is necessary to know the language well. Import __builtins__ and make sure you know it exhaustively. I recently discovered max() this way after having writen if statements to return the larger of two numbers. Code that uses syntax, builtins, and stdlib well could still be unpythonic - but reinventing the wheel definitely is!
blog comments powered by Disqus