@@ -7,7 +7,7 @@ Why does Python use indentation for grouping of statements?
77
88Guido van Rossum believes that using indentation for grouping is extremely
99elegant and contributes a lot to the clarity of the average Python program.
10- Most people learn to love this feature after awhile .
10+ Most people learn to love this feature after a while .
1111
1212Since there are no begin/end brackets there cannot be a disagreement between
1313grouping perceived by the parser and the human reader. Occasionally C
@@ -48,7 +48,7 @@ Why are floating point calculations so inaccurate?
4848
4949People are often very surprised by results like this::
5050
51- >>> 1.2- 1.0
51+ >>> 1.2 - 1.0
5252 0.199999999999999996
5353
5454and think it is a bug in Python. It's not. This has nothing to do with Python,
@@ -85,7 +85,7 @@ of some computation to a float with ``==``. Tiny inaccuracies may mean that
8585``== `` fails. Instead, you have to check that the difference between the two
8686numbers is less than a certain threshold::
8787
88- epsilon = 0.0000000000001 # Tiny allowed error
88+ epsilon = 0.0000000000001 # Tiny allowed error
8989 expected_result = 0.4
9090
9191 if expected_result-epsilon <= computation() <= expected_result+epsilon:
@@ -131,24 +131,25 @@ still useful in those languages, too.
131131Second, it means that no special syntax is necessary if you want to explicitly
132132reference or call the method from a particular class. In C++, if you want to
133133use a method from a base class which is overridden in a derived class, you have
134- to use the ``:: `` operator -- in Python you can write baseclass.methodname(self,
135- <argument list>). This is particularly useful for :meth: `__init__ ` methods, and
136- in general in cases where a derived class method wants to extend the base class
137- method of the same name and thus has to call the base class method somehow.
134+ to use the ``:: `` operator -- in Python you can write
135+ ``baseclass.methodname(self, <argument list>) ``. This is particularly useful
136+ for :meth: `__init__ ` methods, and in general in cases where a derived class
137+ method wants to extend the base class method of the same name and thus has to
138+ call the base class method somehow.
138139
139140Finally, for instance variables it solves a syntactic problem with assignment:
140141since local variables in Python are (by definition!) those variables to which a
141- value assigned in a function body (and that aren't explicitly declared global),
142- there has to be some way to tell the interpreter that an assignment was meant to
143- assign to an instance variable instead of to a local variable, and it should
144- preferably be syntactic (for efficiency reasons). C++ does this through
142+ value is assigned in a function body (and that aren't explicitly declared
143+ global), there has to be some way to tell the interpreter that an assignment was
144+ meant to assign to an instance variable instead of to a local variable, and it
145+ should preferably be syntactic (for efficiency reasons). C++ does this through
145146declarations, but Python doesn't have declarations and it would be a pity having
146- to introduce them just for this purpose. Using the explicit " self.var" solves
147+ to introduce them just for this purpose. Using the explicit `` self.var `` solves
147148this nicely. Similarly, for using instance variables, having to write
148- " self.var" means that references to unqualified names inside a method don't have
149- to search the instance's directories. To put it another way, local variables
150- and instance variables live in two different namespaces, and you need to tell
151- Python which namespace to use.
149+ `` self.var `` means that references to unqualified names inside a method don't
150+ have to search the instance's directories. To put it another way, local
151+ variables and instance variables live in two different namespaces, and you need
152+ to tell Python which namespace to use.
152153
153154
154155Why can't I use an assignment in an expression?
@@ -271,26 +272,13 @@ a string method, since in that case it is easy to see that ::
271272 "1, 2, 4, 8, 16".split(", ")
272273
273274is an instruction to a string literal to return the substrings delimited by the
274- given separator (or, by default, arbitrary runs of white space). In this case a
275- Unicode string returns a list of Unicode strings, an ASCII string returns a list
276- of ASCII strings, and everyone is happy.
275+ given separator (or, by default, arbitrary runs of white space).
277276
278277:meth: `~str.join ` is a string method because in using it you are telling the
279278separator string to iterate over a sequence of strings and insert itself between
280279adjacent elements. This method can be used with any argument which obeys the
281280rules for sequence objects, including any new classes you might define yourself.
282-
283- Because this is a string method it can work for Unicode strings as well as plain
284- ASCII strings. If ``join() `` were a method of the sequence types then the
285- sequence types would have to decide which type of string to return depending on
286- the type of the separator.
287-
288- .. XXX remove next paragraph eventually
289-
290- If none of these arguments persuade you, then for the moment you can continue to
291- use the ``join() `` function from the string module, which allows you to write ::
292-
293- string.join(['1', '2', '4', '8', '16'], ", ")
281+ Similar methods exist for bytes and bytearray objects.
294282
295283
296284How fast are exceptions?
@@ -300,19 +288,19 @@ A try/except block is extremely efficient. Actually catching an exception is
300288expensive. In versions of Python prior to 2.0 it was common to use this idiom::
301289
302290 try:
303- value = dict [key]
291+ value = mydict [key]
304292 except KeyError:
305- dict [key] = getvalue(key)
306- value = dict [key]
293+ mydict [key] = getvalue(key)
294+ value = mydict [key]
307295
308296This only made sense when you expected the dict to have the key almost all the
309297time. If that wasn't the case, you coded it like this::
310298
311- if key in dict (key):
312- value = dict [key]
299+ if mydict.has_key (key):
300+ value = mydict [key]
313301 else:
314- dict [key] = getvalue(key)
315- value = dict [key]
302+ mydict [key] = getvalue(key)
303+ value = mydict [key]
316304
317305For this specific case, you could also use ``value = dict.setdefault(key,
318306getvalue(key)) ``, but only if the ``getvalue() `` call is cheap enough because it
@@ -393,7 +381,7 @@ Can Python be compiled to machine code, C or some other language?
393381-----------------------------------------------------------------
394382
395383Not easily. Python's high level data types, dynamic typing of objects and
396- run-time invocation of the interpreter (using :func: `eval ` or :keyword : `exec `)
384+ run-time invocation of the interpreter (using :func: `eval ` or :func : `exec `)
397385together mean that a "compiled" Python program would probably consist mostly of
398386calls into the Python run-time system, even for seemingly simple operations like
399387``x+1 ``.
@@ -435,7 +423,7 @@ code in various ways to increase performance. See, for example, `Psyco
435423<http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/> `_, `PyInline
436424<http://pyinline.sourceforge.net/> `_, `Py2Cmod
437425<http://sourceforge.net/projects/py2cmod/> `_, and `Weave
438- <http://www.scipy.org/site_content/weave > `_.
426+ <http://www.scipy.org/Weave > `_.
439427
440428
441429How does Python manage memory?
@@ -453,19 +441,20 @@ Jython relies on the Java runtime so the JVM's garbage collector is used. This
453441difference can cause some subtle porting problems if your Python code depends on
454442the behavior of the reference counting implementation.
455443
456- Sometimes objects get stuck in tracebacks temporarily and hence are not
457- deallocated when you might expect. Clear the tracebacks with::
444+ .. XXX relevant for Python 3?
458445
459- import sys
460- sys.exc_clear()
461- sys.exc_traceback = sys.last_traceback = None
446+ Sometimes objects get stuck in traceback temporarily and hence are not
447+ deallocated when you might expect. Clear the traceback with::
462448
463- Tracebacks are used for reporting errors, implementing debuggers and related
464- things. They contain a portion of the program state extracted during the
465- handling of an exception (usually the most recent exception).
449+ import sys
450+ sys.last_traceback = None
466451
467- In the absence of circularities and tracebacks, Python programs need not
468- explicitly manage memory.
452+ Tracebacks are used for reporting errors, implementing debuggers and related
453+ things. They contain a portion of the program state extracted during the
454+ handling of an exception (usually the most recent exception).
455+
456+ In the absence of circularities, Python programs do not need to manage memory
457+ explicitly.
469458
470459Why doesn't Python use a more traditional garbage collection scheme? For one
471460thing, this is not a C standard feature and hence it's not portable. (Yes, we
@@ -484,19 +473,19 @@ implements malloc() and free() properly.
484473In Jython, the following code (which is fine in CPython) will probably run out
485474of file descriptors long before it runs out of memory::
486475
487- for file in <very long list of files> :
476+ for file in very_long_list_of_files :
488477 f = open(file)
489478 c = f.read(1)
490479
491480Using the current reference counting and destructor scheme, each new assignment
492481to f closes the previous file. Using GC, this is not guaranteed. If you want
493482to write code that will work with any Python implementation, you should
494- explicitly close the file; this will work regardless of GC::
483+ explicitly close the file or use the :keyword: `with ` statement; this will work
484+ regardless of GC::
495485
496- for file in <very long list of files>:
497- f = open(file)
498- c = f.read(1)
499- f.close()
486+ for file in very_long_list_of_files:
487+ with open(file) as f:
488+ c = f.read(1)
500489
501490
502491Why isn't all memory freed when Python exits?
@@ -592,10 +581,10 @@ Some unacceptable solutions that have been proposed:
592581- Hash lists by their address (object ID). This doesn't work because if you
593582 construct a new list with the same value it won't be found; e.g.::
594583
595- d = {[1,2]: '12'}
596- print d [[1,2]]
584+ mydict = {[1, 2]: '12'}
585+ print(mydict [[1, 2]])
597586
598- would raise a KeyError exception because the id of the ``[1,2] `` used in the
587+ would raise a KeyError exception because the id of the ``[1, 2] `` used in the
599588 second line differs from that in the first line. In other words, dictionary
600589 keys should be compared using ``== ``, not using :keyword: `is `.
601590
@@ -616,32 +605,32 @@ Some unacceptable solutions that have been proposed:
616605
617606There is a trick to get around this if you need to, but use it at your own risk:
618607You can wrap a mutable structure inside a class instance which has both a
619- :meth: `__cmp_ ` and a :meth: `__hash__ ` method. You must then make sure that the
608+ :meth: `__eq__ ` and a :meth: `__hash__ ` method. You must then make sure that the
620609hash value for all such wrapper objects that reside in a dictionary (or other
621610hash based structure), remain fixed while the object is in the dictionary (or
622611other structure). ::
623612
624613 class ListWrapper:
625614 def __init__(self, the_list):
626615 self.the_list = the_list
627- def __cmp__ (self, other):
616+ def __eq__ (self, other):
628617 return self.the_list == other.the_list
629618 def __hash__(self):
630619 l = self.the_list
631620 result = 98767 - len(l)*555
632- for i in range(len(l) ):
621+ for i, el in enumerate(l ):
633622 try:
634- result = result + (hash(l[i] ) % 9999999) * 1001 + i
635- except:
623+ result = result + (hash(el ) % 9999999) * 1001 + i
624+ except Exception :
636625 result = (result % 7777777) + i * 333
637626 return result
638627
639628Note that the hash computation is complicated by the possibility that some
640629members of the list may be unhashable and also by the possibility of arithmetic
641630overflow.
642631
643- Furthermore it must always be the case that if ``o1 == o2 `` (ie ``o1.__cmp__ (o2)
644- == 0 ``) then ``hash(o1) == hash(o2) `` (ie, ``o1.__hash__() == o2.__hash__() ``),
632+ Furthermore it must always be the case that if ``o1 == o2 `` (ie ``o1.__eq__ (o2)
633+ is True ``) then ``hash(o1) == hash(o2) `` (ie, ``o1.__hash__() == o2.__hash__() ``),
645634regardless of whether the object is in a dictionary or not. If you fail to meet
646635these restrictions dictionaries and other hash based structures will misbehave.
647636
@@ -664,8 +653,8 @@ In Python 2.4 a new builtin -- :func:`sorted` -- has been added. This function
664653creates a new list from a provided iterable, sorts it and returns it. For
665654example, here's how to iterate over the keys of a dictionary in sorted order::
666655
667- for key in sorted(dict.iterkeys() ):
668- ... # do whatever with dict [key]...
656+ for key in sorted(mydict ):
657+ ... # do whatever with mydict [key]...
669658
670659
671660How do you specify and enforce an interface spec in Python?
@@ -714,14 +703,14 @@ Why are default values shared between objects?
714703
715704This type of bug commonly bites neophyte programmers. Consider this function::
716705
717- def foo(D ={}): # Danger: shared reference to one dict for all calls
706+ def foo(mydict ={}): # Danger: shared reference to one dict for all calls
718707 ... compute something ...
719- D [key] = value
720- return D
708+ mydict [key] = value
709+ return mydict
721710
722- The first time you call this function, ``D `` contains a single item. The second
723- time, ``D `` contains two items because when ``foo() `` begins executing, `` D ``
724- starts out with an item already in it.
711+ The first time you call this function, ``mydict `` contains a single item. The
712+ second time, ``mydict `` contains two items because when ``foo() `` begins
713+ executing, `` mydict `` starts out with an item already in it.
725714
726715It is often expected that a function call creates new objects for default
727716values. This is not what happens. Default values are created exactly once, when
@@ -737,14 +726,14 @@ objects as default values. Instead, use ``None`` as the default value and
737726inside the function, check if the parameter is ``None `` and create a new
738727list/dictionary/whatever if it is. For example, don't write::
739728
740- def foo(dict ={}):
729+ def foo(mydict ={}):
741730 ...
742731
743732but::
744733
745- def foo(dict =None):
746- if dict is None:
747- dict = {} # create a new dict for local namespace
734+ def foo(mydict =None):
735+ if mydict is None:
736+ mydict = {} # create a new dict for local namespace
748737
749738This feature can be useful. When you have a function that's time-consuming to
750739compute, a common technique is to cache the parameters and the resulting value
@@ -773,13 +762,13 @@ function calls. Many feel that exceptions can conveniently emulate all
773762reasonable uses of the "go" or "goto" constructs of C, Fortran, and other
774763languages. For example::
775764
776- class label: pass # declare a label
765+ class label: pass # declare a label
777766
778767 try:
779768 ...
780- if (condition): raise label() # goto label
769+ if (condition): raise label() # goto label
781770 ...
782- except label: # where to goto
771+ except label: # where to goto
783772 pass
784773 ...
785774
@@ -804,7 +793,7 @@ r-strings are used for their intended purpose.
804793If you're trying to build Windows pathnames, note that all Windows system calls
805794accept forward slashes too::
806795
807- f = open("/mydir/file.txt") # works fine!
796+ f = open("/mydir/file.txt") # works fine!
808797
809798If you're trying to build a pathname for a DOS command, try e.g. one of ::
810799
@@ -841,7 +830,7 @@ For instance, take the following incomplete snippet::
841830
842831 def foo(a):
843832 with a:
844- print x
833+ print(x)
845834
846835The snippet assumes that "a" must have a member attribute called "x". However,
847836there is nothing in Python that tells the interpreter this. What should happen
@@ -852,21 +841,20 @@ makes such choices much harder.
852841The primary benefit of "with" and similar language features (reduction of code
853842volume) can, however, easily be achieved in Python by assignment. Instead of::
854843
855- function(args).dict [index][index].a = 21
856- function(args).dict [index][index].b = 42
857- function(args).dict [index][index].c = 63
844+ function(args).mydict [index][index].a = 21
845+ function(args).mydict [index][index].b = 42
846+ function(args).mydict [index][index].c = 63
858847
859848write this::
860849
861- ref = function(args).dict [index][index]
850+ ref = function(args).mydict [index][index]
862851 ref.a = 21
863852 ref.b = 42
864853 ref.c = 63
865854
866855This also has the side-effect of increasing execution speed because name
867856bindings are resolved at run-time in Python, and the second version only needs
868- to perform the resolution once. If the referenced object does not have a, b and
869- c attributes, of course, the end result is still a run-time exception.
857+ to perform the resolution once.
870858
871859
872860Why are colons required for the if/while/def/class statements?
@@ -876,12 +864,12 @@ The colon is required primarily to enhance readability (one of the results of
876864the experimental ABC language). Consider this::
877865
878866 if a == b
879- print a
867+ print(a)
880868
881869versus ::
882870
883871 if a == b:
884- print a
872+ print(a)
885873
886874Notice how the second one is slightly easier to read. Notice further how a
887875colon sets off the example in this FAQ answer; it's a standard usage in English.
0 commit comments