Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

What is "Un-Pythonic"?

DZone's Guide to

What is "Un-Pythonic"?

· Web Dev Zone ·
Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

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. 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!

 

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}