46

Doing a google search for "pythonic" reveals a wide range of interpretations. The wikipedia page says:

A common neologism in the Python community is pythonic, which can have a wide range of meanings related to program style. To say that code is pythonic is to say that it uses Python idioms well, that it is natural or shows fluency in the language. Likewise, to say of an interface or language feature that it is pythonic is to say that it works well with Python idioms, that its use meshes well with the rest of the language.

It also discusses the term "unpythonic":

In contrast, a mark of unpythonic code is that it attempts to write C++ (or Lisp, Perl, or Java) code in Python—that is, provides a rough transcription rather than an idiomatic translation of forms from another language. The concept of pythonicity is tightly bound to Python's minimalist philosophy of readability and avoiding the "there's more than one way to do it" approach. Unreadable code or incomprehensible idioms are unpythonic.

What does the term "pythonic" mean? How do I learn to effectively apply it in practice?

6
  • 6
    I think your question can be extended to any programming language. There is always a recommended way of programming which might be accurate in a large number of cases and also to improve revision, readability and maintenance. I think also challenging those recommendations can make a language evolve and advance...
    – Amine
    Commented Nov 15, 2011 at 18:46
  • @Amine so true. Actually I think a community wiki consisting of precisely where to learn language idioms - for all languages - should be considered. Commented Nov 15, 2011 at 18:51
  • Possibly related: programmers.stackexchange.com/questions/47860/… Commented Nov 15, 2011 at 18:57
  • 1
    Commenters: please stop posting irrelevant comments; they've been deleted for a reason. If you have an answer, leave it as an answer. If you want to discuss the topic of this question, please use chat.
    – user8
    Commented Nov 15, 2011 at 21:56
  • 1
    By practicing Python!
    – Dynamic
    Commented Nov 15, 2011 at 22:32

8 Answers 8

22

I've found that a most people have their own interpretations of what being "Pythonic" really means. From Wikipedia:

A common neologism in the Python community is pythonic, which can have a wide range of meanings related to program style. To say that code is pythonic is to say that it uses Python idioms well, that it is natural or shows fluency in the language. Likewise, to say of an interface or language feature that it is pythonic is to say that it works well with Python idioms, that its use meshes well with the rest of the language.

In contrast, a mark of unpythonic code is that it attempts to write C++ (or Lisp, Perl, or Java) code in Python—that is, provides a rough transcription rather than an idiomatic translation of forms from another language. The concept of pythonicity is tightly bound to Python's minimalist philosophy of readability and avoiding the "there's more than one way to do it" approach. Unreadable code or incomprehensible idioms are unpythonic.

I've found that more times than not, more "pythonic" examples are actually derived from people trying to be clever with Python idioms and (again, more times than not) rendering their code virtually unreadable (which is not Pythonic).

As long as you're sticking to Python's idioms and avoiding trying to use C++ (or other language) styles in Python, then you're being Pythonic.

As pointed out by WorldEngineer, PEP8 is a good standard to follow (and if you use VIM, there are plugins available for PEP8 linting).


Really though, at the end of the day, if your solution works and isn't absolutely horribly un-maintainable and slow, who cares? More times than not, your job is to get a task done, not write the most elegant, pythonic code possible.


Another side note (just my opinion, feel free to downvote because of it ;)): I've also found the Python community to be filled with a ton of ego (not that most communities aren't, it's just a little more prevalent in communities such as C and Python). So, combining the ego with misconstrued interpretations of being "pythonic" will tend to yield a whole lot of baseless negativity. Take what you read from others with a grain of salt. Stick to official standards and documentation and you'll be fine.

3
  • 2
    +1 for a nice answer (except for the quote since I used it in the OP).
    – user39685
    Commented Nov 15, 2011 at 19:38
  • Ugh.. Shoulda re-read the OP before posting the quote :P Commented Nov 15, 2011 at 19:44
  • 3
    Rather, there's a high correlation between ego and being active online, voicing opinions in any community. Basically you don't see the non-egoistic people that much because they don't write that much in the first place.
    – isarandi
    Commented Apr 10, 2015 at 12:22
16

Pythonic is to code idiomatically in Python. It means using structures and formatting that work well for Python from a programming standpoint but also from a community reading standpoint. It's very much like how K&R set the standard for C programming style for a long time. This guide shows you have to code idiomatically in Python. PEP 8 is referenced in that guide so it's probably worth reading.

2
  • 1
    @MattFenwick Isn't that 90% of what programming is about though? Good programmers spend lots of time reading of code and in what time remains, write lots of code. The more Pythonic code you read, and the more you write in Python, the more Pythonic your code will be. I don't think there are any shortcuts here. Commented Nov 15, 2011 at 21:53
  • 2
    Excellent link! Commented Jan 11, 2012 at 17:52
13

Writing "Pythonic" code IMHO is just making effective use of the (V)HLL features the language provides. As an ubiquitous example,

x, y = 7, 'fuhrer'

That is very Pythonic. I remember when I started learning C# after months of only Python,

int x, y = 10, z;

somehow confused me, but it took a minute for me to return to my C/C++ roots.

Another Pythonic way is using lambdas.

l = [1, 2, 3, 4, 5]
print(sorted(l, key=lambda x: -x))

will actually print l sorted in descending order.

Then there is the very much used, but very less understood "duck typing" - If it walks and talks like a duck, you treat it as a duck. This is loosely related to interfaces in other OO languages.

Also using functional programming methods where applicable, such as the use of map and reduce are considered pythonic.

I saw an answer being posted as I was typing, and it contains a nice link. PS: It's not that your knowledge of Python is limited. I can bet that Python was not your first language, and hence, (like most of us pythonistas) you'll have to learn to get "idiomatic" with the snake! Cheers!

7
  • I did not include the link as it already was posted as I was typing - WorldEngineer's answer :) Just think of "exploiting" the language features for your and others' good, and you'll get Pythonic on the way, and please do follow that link Commented Nov 15, 2011 at 19:01
  • 4
    Actually, many dispute that map, reduce, lambda and such are idiomatic per se. List comprehensions and generator expression are an alternative and many prefer them whenever reasonably possible (in particular, they are less noisy when you'd need a lambda anyway). They certainly have their uses, and functional programming shows in other idioms (decorator for instance).
    – user7043
    Commented Nov 15, 2011 at 19:38
  • @delnan agreed - and even more so when it comes to Python 3. Conclusion is that the functional features should be used exactly where required. And that (There's only one obvious way of doing it) is idiomatic :) Commented Nov 15, 2011 at 19:45
  • Personally, I've never understood people's preferences for your first example. This is far easier to mentally parse (Which is the Zen of Python, code is read more often than it is written): (x, y) = (7, 'fuhrer') - yet I'm almost always "corrected" that without parens is the best way to write it!
    – Izkata
    Commented Jul 3, 2012 at 23:05
  • 2
    I would argue that your specific sorting example is not pythonic. Why reintroduce reordering with a lambda if you can just print(sorted(l, reverse=True)), which additionally explicitly tells the reader what's going on. I would find your first example disputable, too. It's two assignments compressed into one; it's okay, but I wouldn't call it very Pythonic. Readers have to look longer at what it does than compared to having two assignments.
    – phresnel
    Commented May 3, 2014 at 4:46
8
--> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Pythonic code is:

  • Readable
  • Simple (as simple as possible, but no simpler)
  • Well thought-out
1
  • 1
    +1. The Zen of Python is more important for writing pythonic code than following a list of idioms; the latter won't cover all circumstances.
    – Doval
    Commented Mar 18, 2014 at 13:16
6

Anytime I've tried to learn a new language, I've found that reading code by people who know the language like the back of their hand, looking up/asking about anything that looks weird, and then trying to imitate their style is the best thing to do. Examples:

In Python, since we're on the subject, I found the examples from Dive Into Python incredibly useful for getting started. They tend to teach not only the basics of Python, but to really emphasize idiomatic Python.

When learning D, since the documentation wasn't great at the time because the language was so bleeding edge, I learned by reading the code to the standard library, specifically, some of Andrei Alexandrescu's masterpieces.

When learning C++ I inherited a codebase from a pretty good C++ programmer and learned a lot about idiomatic C++ programming from his insistence on passing STL containers by reference, etc.

In all languages, I find that browsing the StackOverflow questions about the language and looking at what people typically do to accomplish basic things helps.

1
  • +1 Once you know the basics of a language, reading code will help far more than reading books.
    – Pace
    Commented Mar 24, 2013 at 16:33
3

Python is not Java might give you some useful advice. Can't say more without know what sort of issues you are running into, but it's very concrete advice for programmers coming from another language (in this case specifically java) background on how to do python differently.

2

Someone said to paraphrase, to learn what is Pythonic, just bash out some code. I disagree with that. If you like writting highly dense code, that doesn't make it more Pythonic.

One way to help you define what is Pythonic as far as yourself is concerned, ask your self "Why would I(meaning you) use the Python language?" What appeals to you about it?

For me it is readability and lack of compiling and open source (pretty much all of it). I can down load tons of libraries and read thier source code with less stress about licensing then many other languages.

To me Python is beautiful visually. Guido (the creator of Python) also keeps proving to me, through his replies in PEPS and discussions) that his choices for how he made the language are superior to my own ideas of how it should have been created.

To me, a great programmer is someone with very informed decision making skills about which way to go when coding. To me, Python aids with making those choices quickly.

By simplifing the source code syntax by allowing duck typing instead of explicid type casting, and the expectation that coders reviewing your code "should be well behaved coders" leads to something I too call "Pythonic"

So there are two sides of what is Pythonic. One is syntactical, the other is the practice of. How to explain the deeper side of what is "Pythonic"..?

In Python it is no big deal to do this: alist = ['one','two','three\n'] alist.append( (1234, 'Atuple') )

and the tuple will be added to the list without any concern for object types. The Pythonic part is not that you CAN do this, but that your code should EXPECT this and just work/adapt.

Whatever works on the -alist- object should be written with the idea that some other coder could come in and add a non-string to the list and that the source code adaptation by the new coder should not be difficult to do. That's the benefit of ducktype after all.

-2

Buy a recommended book. Read it. It should give you a good basis of using the language and in a mechanism that should meet the community style

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.