Over a million developers have joined DZone.

What is "Un-Pythonic"?

DZone's Guide to

What is "Un-Pythonic"?

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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!


Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Simeon Franklin, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}