Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Doc/faq/design.rst

    r2 r391  
    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.
     10Most people learn to love this feature after a while.
    1111
    1212Since there are no begin/end brackets there cannot be a disagreement between
     
    2929least slightly uneasy when reading (or being required to write) another style.
    3030
    31 Many coding styles place begin/end brackets on a line by themself.  This makes
     31Many coding styles place begin/end brackets on a line by themselves.  This makes
    3232programs considerably longer and wastes valuable screen space, making it harder
    3333to get a good overview of a program.  Ideally, a function should fit on one
     
    4949People are often very surprised by results like this::
    5050
    51    >>> 1.2-1.0
     51   >>> 1.2 - 1.0
    5252   0.199999999999999996
    5353
     
    7676that was probably intended::
    7777
    78    >>> 0.2
    79    0.20000000000000001
    80    >>> print 0.2
     78   >>> 1.1 - 0.9
     79   0.20000000000000007
     80   >>> print 1.1 - 0.9
    8181   0.2
    8282
     
    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
     
    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.
     134to use the ``::`` operator -- in Python you can write
     135``baseclass.methodname(self, <argument list>)``.  This is particularly useful
     136for :meth:`__init__` methods, and in general in cases where a derived class
     137method wants to extend the base class method of the same name and thus has to
     138call 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
     142value is assigned in a function body (and that aren't explicitly declared
     143global), there has to be some way to tell the interpreter that an assignment was
     144meant to assign to an instance variable instead of to a local variable, and it
     145should 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
     147to 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
     150have to search the instance's directories.  To put it another way, local
     151variables and instance variables live in two different namespaces, and you need
     152to tell Python which namespace to use.
    152153
    153154
     
    225226that didn't have methods at all (e.g. tuples).  It is also convenient to have a
    226227function that can readily be applied to an amorphous collection of objects when
    227 you use the functional features of Python (``map()``, ``apply()`` et al).
     228you use the functional features of Python (``map()``, ``zip()`` et al).
    228229
    229230In fact, implementing ``len()``, ``max()``, ``min()`` as a built-in function is
     
    235236.. XXX talk about protocols?
    236237
    237 Note that for string operations Python has moved from external functions (the
    238 ``string`` module) to methods.  However, ``len()`` is still a function.
     238.. note::
     239
     240   For string operations, Python has moved from external functions (the
     241   ``string`` module) to methods.  However, ``len()`` is still a function.
    239242
    240243
     
    295298------------------------
    296299
    297 A try/except block is extremely efficient.  Actually catching an exception is
    298 expensive.  In versions of Python prior to 2.0 it was common to use this idiom::
     300A try/except block is extremely efficient if no exceptions are raised.  Actually
     301catching an exception is expensive.  In versions of Python prior to 2.0 it was
     302common to use this idiom::
    299303
    300304   try:
    301        value = dict[key]
     305       value = mydict[key]
    302306   except KeyError:
    303        dict[key] = getvalue(key)
    304        value = dict[key]
     307       mydict[key] = getvalue(key)
     308       value = mydict[key]
    305309
    306310This only made sense when you expected the dict to have the key almost all the
    307311time.  If that wasn't the case, you coded it like this::
    308312
    309    if dict.has_key(key):
    310        value = dict[key]
     313   if key in mydict:
     314       value = mydict[key]
    311315   else:
    312        dict[key] = getvalue(key)
    313        value = dict[key]
    314 
    315 (In Python 2.0 and higher, you can code this as ``value = dict.setdefault(key,
    316 getvalue(key))``.)
     316       value = mydict[key] = getvalue(key)
     317
     318.. note::
     319
     320   In Python 2.0 and higher, you can code this as ``value =
     321   mydict.setdefault(key, getvalue(key))``.
    317322
    318323
     
    366371Answer 2: Fortunately, there is `Stackless Python <http://www.stackless.com>`_,
    367372which has a completely redesigned interpreter loop that avoids the C stack.
    368 It's still experimental but looks very promising.  Although it is binary
    369 compatible with standard Python, it's still unclear whether Stackless will make
    370 it into the core -- maybe it's just too revolutionary.
    371 
    372 
    373 Why can't lambda forms contain statements?
    374 ------------------------------------------
    375 
    376 Python lambda forms cannot contain statements because Python's syntactic
     373
     374
     375Why can't lambda expressions contain statements?
     376------------------------------------------------
     377
     378Python lambda expressions cannot contain statements because Python's syntactic
    377379framework can't handle statements nested inside expressions.  However, in
    378380Python, this is not a serious problem.  Unlike lambda forms in other languages,
     
    381383
    382384Functions are already first class objects in Python, and can be declared in a
    383 local scope.  Therefore the only advantage of using a lambda form instead of a
     385local scope.  Therefore the only advantage of using a lambda instead of a
    384386locally-defined function is that you don't need to invent a name for the
    385387function -- but that's just a local variable to which the function object (which
    386 is exactly the same type of object that a lambda form yields) is assigned!
     388is exactly the same type of object that a lambda expression yields) is assigned!
    387389
    388390
     
    433435<http://pyinline.sourceforge.net/>`_, `Py2Cmod
    434436<http://sourceforge.net/projects/py2cmod/>`_, and `Weave
    435 <http://www.scipy.org/site_content/weave>`_.
     437<http://www.scipy.org/Weave>`_.
    436438
    437439
     
    451453the behavior of the reference counting implementation.
    452454
     455.. XXX relevant for Python 2.6?
     456
    453457Sometimes objects get stuck in tracebacks temporarily and hence are not
    454458deallocated when you might expect.  Clear the tracebacks with::
     
    462466handling of an exception (usually the most recent exception).
    463467
    464 In the absence of circularities and tracebacks, Python programs need not
    465 explicitly manage memory.
     468In the absence of circularities and tracebacks, Python programs do not need to
     469manage memory explicitly.
    466470
    467471Why doesn't Python use a more traditional garbage collection scheme?  For one
     
    482486of file descriptors long before it runs out of memory::
    483487
    484    for file in <very long list of files>:
     488   for file in very_long_list_of_files:
    485489       f = open(file)
    486490       c = f.read(1)
     
    489493to f closes the previous file.  Using GC, this is not guaranteed.  If you want
    490494to write code that will work with any Python implementation, you should
    491 explicitly close the file; this will work regardless of GC::
    492 
    493    for file in <very long list of files>:
    494        f = open(file)
    495        c = f.read(1)
    496        f.close()
     495explicitly close the file or use the :keyword:`with` statement; this will work
     496regardless of GC::
     497
     498   for file in very_long_list_of_files:
     499       with open(file) as f:
     500           c = f.read(1)
    497501
    498502
     
    590594  construct a new list with the same value it won't be found; e.g.::
    591595
    592      d = {[1,2]: '12'}
    593      print d[[1,2]]
    594 
    595   would raise a KeyError exception because the id of the ``[1,2]`` used in the
     596     mydict = {[1, 2]: '12'}
     597     print mydict[[1, 2]]
     598
     599  would raise a KeyError exception because the id of the ``[1, 2]`` used in the
    596600  second line differs from that in the first line.  In other words, dictionary
    597601  keys should be compared using ``==``, not using :keyword:`is`.
     
    614618There is a trick to get around this if you need to, but use it at your own risk:
    615619You can wrap a mutable structure inside a class instance which has both a
    616 :meth:`__cmp_` and a :meth:`__hash__` method.  You must then make sure that the
     620:meth:`__eq__` and a :meth:`__hash__` method.  You must then make sure that the
    617621hash value for all such wrapper objects that reside in a dictionary (or other
    618622hash based structure), remain fixed while the object is in the dictionary (or
     
    622626       def __init__(self, the_list):
    623627           self.the_list = the_list
    624        def __cmp__(self, other):
     628       def __eq__(self, other):
    625629           return self.the_list == other.the_list
    626630       def __hash__(self):
    627631           l = self.the_list
    628632           result = 98767 - len(l)*555
    629            for i in range(len(l)):
     633           for i, el in enumerate(l):
    630634               try:
    631                    result = result + (hash(l[i]) % 9999999) * 1001 + i
    632                except:
     635                   result = result + (hash(el) % 9999999) * 1001 + i
     636               except Exception:
    633637                   result = (result % 7777777) + i * 333
    634638           return result
     
    638642overflow.
    639643
    640 Furthermore it must always be the case that if ``o1 == o2`` (ie ``o1.__cmp__(o2)
    641 == 0``) then ``hash(o1) == hash(o2)`` (ie, ``o1.__hash__() == o2.__hash__()``),
     644Furthermore it must always be the case that if ``o1 == o2`` (ie ``o1.__eq__(o2)
     645is True``) then ``hash(o1) == hash(o2)`` (ie, ``o1.__hash__() == o2.__hash__()``),
    642646regardless of whether the object is in a dictionary or not.  If you fail to meet
    643647these restrictions dictionaries and other hash based structures will misbehave.
     
    663667order::
    664668
    665    for key in sorted(dict.iterkeys()):
    666        ... # do whatever with dict[key]...
     669   for key in sorted(mydict):
     670       ... # do whatever with mydict[key]...
    667671
    668672
     
    678682(ABCs).  You can then use :func:`isinstance` and :func:`issubclass` to check
    679683whether an instance or a class implements a particular ABC.  The
    680 :mod:`collections` modules defines a set of useful ABCs such as
    681 :class:`Iterable`, :class:`Container`, and :class:`MutableMapping`.
     684:mod:`collections` module defines a set of useful ABCs such as
     685:class:`~collections.Iterable`, :class:`~collections.Container`, and
     686:class:`~collections.MutableMapping`.
    682687
    683688For Python, many of the advantages of interface specifications can be obtained
     
    713718This type of bug commonly bites neophyte programmers.  Consider this function::
    714719
    715    def foo(D={}):  # Danger: shared reference to one dict for all calls
     720   def foo(mydict={}):  # Danger: shared reference to one dict for all calls
    716721       ... compute something ...
    717        D[key] = value
    718        return D
    719 
    720 The first time you call this function, ``D`` contains a single item.  The second
    721 time, ``D`` contains two items because when ``foo()`` begins executing, ``D``
    722 starts out with an item already in it.
     722       mydict[key] = value
     723       return mydict
     724
     725The first time you call this function, ``mydict`` contains a single item.  The
     726second time, ``mydict`` contains two items because when ``foo()`` begins
     727executing, ``mydict`` starts out with an item already in it.
    723728
    724729It is often expected that a function call creates new objects for default
     
    736741list/dictionary/whatever if it is.  For example, don't write::
    737742
    738    def foo(dict={}):
     743   def foo(mydict={}):
    739744       ...
    740745
    741746but::
    742747
    743    def foo(dict=None):
    744        if dict is None:
    745            dict = {} # create a new dict for local namespace
     748   def foo(mydict=None):
     749       if mydict is None:
     750           mydict = {} # create a new dict for local namespace
    746751
    747752This feature can be useful.  When you have a function that's time-consuming to
     
    751756
    752757   # Callers will never provide a third parameter for this function.
    753    def expensive (arg1, arg2, _cache={}):
    754        if _cache.has_key((arg1, arg2)):
     758   def expensive(arg1, arg2, _cache={}):
     759       if (arg1, arg2) in _cache:
    755760           return _cache[(arg1, arg2)]
    756761
     
    772777languages.  For example::
    773778
    774    class label: pass # declare a label
     779   class label: pass  # declare a label
    775780
    776781   try:
    777782        ...
    778         if (condition): raise label() # goto label
     783        if condition: raise label() # goto label
    779784        ...
    780    except label: # where to goto
     785   except label:  # where to goto
    781786        pass
    782787   ...
     
    803808accept forward slashes too::
    804809
    805    f = open("/mydir/file.txt") # works fine!
     810   f = open("/mydir/file.txt")  # works fine!
    806811
    807812If you're trying to build a pathname for a DOS command, try e.g. one of ::
     
    820825
    821826   with obj:
    822        a = 1    # equivalent to obj.a = 1
     827       a = 1               # equivalent to obj.a = 1
    823828       total = total + 1   # obj.total = obj.total + 1
    824829
     
    851856volume) can, however, easily be achieved in Python by assignment.  Instead of::
    852857
    853    function(args).dict[index][index].a = 21
    854    function(args).dict[index][index].b = 42
    855    function(args).dict[index][index].c = 63
     858   function(args).mydict[index][index].a = 21
     859   function(args).mydict[index][index].b = 42
     860   function(args).mydict[index][index].c = 63
    856861
    857862write this::
    858863
    859    ref = function(args).dict[index][index]
     864   ref = function(args).mydict[index][index]
    860865   ref.a = 21
    861866   ref.b = 42
     
    864869This also has the side-effect of increasing execution speed because name
    865870bindings are resolved at run-time in Python, and the second version only needs
    866 to perform the resolution once.  If the referenced object does not have a, b and
    867 c attributes, of course, the end result is still a run-time exception.
     871to perform the resolution once.
    868872
    869873
     
    908912When you have a literal value for a list, tuple, or dictionary spread across
    909913multiple lines, it's easier to add more elements because you don't have to
    910 remember to add a comma to the previous line.  The lines can also be sorted in
    911 your editor without creating a syntax error.
     914remember to add a comma to the previous line.  The lines can also be reordered
     915without creating a syntax error.
    912916
    913917Accidentally omitting the comma can lead to errors that are hard to diagnose.
Note: See TracChangeset for help on using the changeset viewer.