What does {!r} mean in Python?

What do different aphorisms in The Zen of Python mean?

  • It'd be great if you could substantiate and clarify each point with actual code example containing both bad and good ways of doing something. Quoting http://www.python.org/dev/peps/pep-0020/: 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!

  • Answer:

    Beautiful is better than ugly. Logical operators - Use of and, or instead of &&, || respectively. Though it is subjective, code seems more readable and beautiful this way. if (is_valid(a) && b == 0 || s == 'yes') { versus if is_valid(a) and b == 0 or s == 'yes': It goes well with Don't make me think philosophy. Euclids Algorithm to find the greatest common denominator in 4 lines: def gcd(x, y): while y: x, y = y, x % y return x Of course, the mathematical beauty comes from the algorithm, but I love the way Python succeeds at being precise, concise, explicit and elegant at the same time. Explicit is better than implicit. Every time you invoke a function you should name its module explicitly: import os print os.getcwd() instead of this from os import * print getcwd() In case you forget this best practice, let the last koan remind it to you: Namespaces are one honking great idea - let's do more of those! Another example: the 'self' parameter in methods. You always have to mention explicitly what object you are working with. Here's another example of Explicit is better than implicit, applied to the language itself. While Python is http://en.wikipedia.org/wiki/Dynamic_typing#Dynamic_typing, it is also http://en.wikipedia.org/wiki/Strongly_typed_programming_language. Several scripting languages allow things like this: <?php $foo = "5"; echo $foo * 3; ?> [$]> php test.php 15% (The % is a result of me not adding a newline to the end of the echo statement.) This is known as http://en.wikipedia.org/wiki/Type_conversion#Implicit_type_conversion. You'll also see it used frequently in C, where programmers often take advantage of the compiler's lack of caring to put bits in places they don't belong (as viewed by someone like me :) ). Now, in Python, multiplying a string by an integer will print the string that many times: >>> foo = "5" >>> foo * 3 '555' because Guido decided to override that particular operator. Adding them, however, >>> foo+3 Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects produces an exception. If you really want to do so, then you need to tell Python that, dammit, you want an integer. >>>int(foo)+3 8 Sparse is better than dense. if i>0: return sqrt(i) elif i==0: return 0 else: return 1j * sqrt(-i) versus if i > 0: return sqrt(i) elif i == 0: return 0 else: return 1j * sqrt(-i) To rephrase the dictum another way, "Don't try to stick too much code on one line." Readability Counts. The easy one :D. Compare C and Python: #include <stdio.h> int main(void) { printf("Hello, world!\n"); return(0); } print "Hello world!" And what about indentation? Well-indented code is more readable. Thus, in Python it's mandatory. Errors should never pass silently. try: import this except ImportError: print 'this is not available' Unless explicitly silenced. try: v = d[k] except KeyError: v = d[k] = default In the face of ambiguity, refuse the temptation to guess. Consider: if not a and b: do something What binds more tightly 'not' or 'and'? The syntax is unambiguous but my memory is not. Could it be? (no): if not (a and b): do something If short-circuiting doesn't matter then I'd write it: if b and not a: do something Or somewhat ugly but reliable if it does: if (not a) and b: do something This is subjective because someone may argue that you should expect the reader of your code to know Python and thus the priorities for 'not' and 'and', and it is not obscure enough to justify parentheses. There should be one - and preferably only one - obvious way to do it. (The exact contrary of http://www.perl.org/'s motto - there's more than one way to do it). How many ways could you provide to "iterate over a sequence" in C++? Iterating over an array with integers or pointers; iterating over STL vectors with various kinds of iterators... etc. If you want to be proficient in C++ (and be able to read other people's code), you must learn them all. In Python you must learn only one: for element in sequence: And isn't it obvious? There should be one module for every need. Although that way may not be obvious at first unless you're Dutch. OK this mostly refers to http://en.wikipedia.org/wiki/Guido_van_Rossum. The classic trinary if-then-else operator (it's a=cond?expr1:expr2 in C) was debated hotly. Guido came up with this a = expr1 if cond else expr2 This is the one way to do this, and it isn't obvious at first. One of the sidebars for this is always the observation that the condition is evaluated first irrespective of the left-to-right order of the operands. Now is better than never. Never: f = open('i_will_stay_open_for_ages.txt', 'w') f.write('every even number > 2 is the sum of two primes') assert not 'this sentence is false' f.close() Now: with open('i_will_be_closed_right_away.txt', 'w') as f: f.write('the sum of two primes > 2 is an even number') raise AssertionError('this sentence is false') In the first example, an exception will bump you out of the codeblock before the file can be closed. In the second, python will politely handle this for you with http://www.python.org/dev/peps/pep-0343/. You could of course fix the first case by using try: and finally: blocks, but beautiful is better than ugly. This answer is compiled from various sources over the Internet. I think Hunter Blanks does a better job of this than I could in http://artifex.org/~hblanks/talks/2011/pep20_by_example.html

Soumya Ghosh at Quora Visit the source

Was this solution helpful to you?

Other answers

Hi, I made a presentation with answer. Check it at : http://www.slideshare.net/chirilasorina/the-zen-of-python-53161452 Insights:

Chirila Sorina

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.