Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does pythonic mean? [closed]

Tags:

python

On many websites I often see comments that code isn't Pythonic, or that there is a more Pythonic way to achieve the same goal.

What does Pythonic mean in this context? For example, why is

while i < someValue:
   do_something(list[i])
   i += 1

not Pythonic while

for x in list:
   doSomething(x)

is Pythonic?

like image 629
Jon Avatar asked Oct 16 '22 05:10

Jon


People also ask

What it means to be Pythonic?

In short, “pythonic” describes a coding style that leverages Python's unique features to write code that is readable and beautiful.

How long should a Python function be?

A function should be small because it is easier to know what the function does. How small is small? There should rarely be more than 20 lines of code in one function.


1 Answers

Exploiting the features of the Python language to produce code that is clear, concise and maintainable.

Pythonic means code that doesn't just get the syntax right, but that follows the conventions of the Python community and uses the language in the way it is intended to be used.

This is maybe easiest to explain by negative example, as in the linked article from the other answers. Examples of un-Pythonic code often come from users of other languages, who instead of learning a Python programming patterns such as list comprehensions or generator expressions, attempt to crowbar in patterns more commonly used in C or Java. Loops are particularly common examples of this.

For example, in Java I might use

for(int index=0; index < items.length; index++) {
     items[index].performAction();
}

In Python we can try and replicate this using while loops, but it would be cleaner to use:

for item in items:
  item.perform_action()

Or, even a generator expression

(item.some_attribute for item in items)

So essentially when someone says something is un-Pythonic, they are saying that the code could be rewritten in a way that is a better fit for Python's coding style.

Typing import this at the command line gives a summary of Python principles. Less well known is that the source code for import this is decidedly, and by design, un-Pythonic! Take a look at it for an example of what not to do.

like image 140
James Avatar answered Nov 10 '22 00:11

James