What is "Un-Pythonic"?
Join the DZone community and get the full member experience.
Join For FreeI 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. Built-in 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 built-in 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 built-in support for is un-pythonic. 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!
Published at DZone with permission of Simeon Franklin, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments