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?

8 Answers8

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.

Demian Brecht
  • 17,585
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.

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!

yati sagade
  • 2,089
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
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.

dsimcha
  • 17,284
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.

maxpolun
  • 418
  • 2
  • 4
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.

DevPlayer
  • 216
-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

Paul
  • 730