Over a million developers have joined DZone.

What is "Un-Pythonic"?

DZone's Guide to

What is "Un-Pythonic"?

· Web Dev Zone ·
Free Resource

Building real-time chat? Enroll in a Free Course on Mobile Chat Development. 

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 == "":
if len(x) == 0:

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):

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!


Power realtime chat, IoT and messaging apps at scale. Pubsub realtime messaging, functions, chat, presence, push, notifications, blocks catalog and more.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}