Changeset 391 for python/trunk/Doc/faq/design.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/faq/design.rst
r2 r391 8 8 Guido van Rossum believes that using indentation for grouping is extremely 9 9 elegant and contributes a lot to the clarity of the average Python program. 10 Most people learn to love this feature after a while.10 Most people learn to love this feature after a while. 11 11 12 12 Since there are no begin/end brackets there cannot be a disagreement between … … 29 29 least slightly uneasy when reading (or being required to write) another style. 30 30 31 Many coding styles place begin/end brackets on a line by themsel f. This makes31 Many coding styles place begin/end brackets on a line by themselves. This makes 32 32 programs considerably longer and wastes valuable screen space, making it harder 33 33 to get a good overview of a program. Ideally, a function should fit on one … … 49 49 People are often very surprised by results like this:: 50 50 51 >>> 1.2 -1.051 >>> 1.2 - 1.0 52 52 0.199999999999999996 53 53 … … 76 76 that was probably intended:: 77 77 78 >>> 0.279 0.2000000000000000 180 >>> print 0.278 >>> 1.1 - 0.9 79 0.20000000000000007 80 >>> print 1.1 - 0.9 81 81 0.2 82 82 … … 86 86 numbers is less than a certain threshold:: 87 87 88 epsilon = 0.0000000000001 # Tiny allowed error88 epsilon = 0.0000000000001 # Tiny allowed error 89 89 expected_result = 0.4 90 90 … … 132 132 reference or call the method from a particular class. In C++, if you want to 133 133 use 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. 138 139 139 140 Finally, for instance variables it solves a syntactic problem with assignment: 140 141 since 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 through142 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 145 146 declarations, 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"solves147 to introduce them just for this purpose. Using the explicit ``self.var`` solves 147 148 this 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. 152 153 153 154 … … 225 226 that didn't have methods at all (e.g. tuples). It is also convenient to have a 226 227 function that can readily be applied to an amorphous collection of objects when 227 you use the functional features of Python (``map()``, `` apply()`` et al).228 you use the functional features of Python (``map()``, ``zip()`` et al). 228 229 229 230 In fact, implementing ``len()``, ``max()``, ``min()`` as a built-in function is … … 235 236 .. XXX talk about protocols? 236 237 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. 239 242 240 243 … … 295 298 ------------------------ 296 299 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:: 300 A try/except block is extremely efficient if no exceptions are raised. Actually 301 catching an exception is expensive. In versions of Python prior to 2.0 it was 302 common to use this idiom:: 299 303 300 304 try: 301 value = dict[key]305 value = mydict[key] 302 306 except KeyError: 303 dict[key] = getvalue(key)304 value = dict[key]307 mydict[key] = getvalue(key) 308 value = mydict[key] 305 309 306 310 This only made sense when you expected the dict to have the key almost all the 307 311 time. If that wasn't the case, you coded it like this:: 308 312 309 if dict.has_key(key):310 value = dict[key]313 if key in mydict: 314 value = mydict[key] 311 315 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))``. 317 322 318 323 … … 366 371 Answer 2: Fortunately, there is `Stackless Python <http://www.stackless.com>`_, 367 372 which 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 375 Why can't lambda expressions contain statements? 376 ------------------------------------------------ 377 378 Python lambda expressions cannot contain statements because Python's syntactic 377 379 framework can't handle statements nested inside expressions. However, in 378 380 Python, this is not a serious problem. Unlike lambda forms in other languages, … … 381 383 382 384 Functions are already first class objects in Python, and can be declared in a 383 local scope. Therefore the only advantage of using a lambda forminstead of a385 local scope. Therefore the only advantage of using a lambda instead of a 384 386 locally-defined function is that you don't need to invent a name for the 385 387 function -- but that's just a local variable to which the function object (which 386 is exactly the same type of object that a lambda formyields) is assigned!388 is exactly the same type of object that a lambda expression yields) is assigned! 387 389 388 390 … … 433 435 <http://pyinline.sourceforge.net/>`_, `Py2Cmod 434 436 <http://sourceforge.net/projects/py2cmod/>`_, and `Weave 435 <http://www.scipy.org/ site_content/weave>`_.437 <http://www.scipy.org/Weave>`_. 436 438 437 439 … … 451 453 the behavior of the reference counting implementation. 452 454 455 .. XXX relevant for Python 2.6? 456 453 457 Sometimes objects get stuck in tracebacks temporarily and hence are not 454 458 deallocated when you might expect. Clear the tracebacks with:: … … 462 466 handling of an exception (usually the most recent exception). 463 467 464 In the absence of circularities and tracebacks, Python programs need not465 explicitly manage memory.468 In the absence of circularities and tracebacks, Python programs do not need to 469 manage memory explicitly. 466 470 467 471 Why doesn't Python use a more traditional garbage collection scheme? For one … … 482 486 of file descriptors long before it runs out of memory:: 483 487 484 for file in <very long list of files>:488 for file in very_long_list_of_files: 485 489 f = open(file) 486 490 c = f.read(1) … … 489 493 to f closes the previous file. Using GC, this is not guaranteed. If you want 490 494 to 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()495 explicitly close the file or use the :keyword:`with` statement; this will work 496 regardless of GC:: 497 498 for file in very_long_list_of_files: 499 with open(file) as f: 500 c = f.read(1) 497 501 498 502 … … 590 594 construct a new list with the same value it won't be found; e.g.:: 591 595 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 the596 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 596 600 second line differs from that in the first line. In other words, dictionary 597 601 keys should be compared using ``==``, not using :keyword:`is`. … … 614 618 There is a trick to get around this if you need to, but use it at your own risk: 615 619 You 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 the620 :meth:`__eq__` and a :meth:`__hash__` method. You must then make sure that the 617 621 hash value for all such wrapper objects that reside in a dictionary (or other 618 622 hash based structure), remain fixed while the object is in the dictionary (or … … 622 626 def __init__(self, the_list): 623 627 self.the_list = the_list 624 def __ cmp__(self, other):628 def __eq__(self, other): 625 629 return self.the_list == other.the_list 626 630 def __hash__(self): 627 631 l = self.the_list 628 632 result = 98767 - len(l)*555 629 for i in range(len(l)):633 for i, el in enumerate(l): 630 634 try: 631 result = result + (hash( l[i]) % 9999999) * 1001 + i632 except :635 result = result + (hash(el) % 9999999) * 1001 + i 636 except Exception: 633 637 result = (result % 7777777) + i * 333 634 638 return result … … 638 642 overflow. 639 643 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__()``),644 Furthermore it must always be the case that if ``o1 == o2`` (ie ``o1.__eq__(o2) 645 is True``) then ``hash(o1) == hash(o2)`` (ie, ``o1.__hash__() == o2.__hash__()``), 642 646 regardless of whether the object is in a dictionary or not. If you fail to meet 643 647 these restrictions dictionaries and other hash based structures will misbehave. … … 663 667 order:: 664 668 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]... 667 671 668 672 … … 678 682 (ABCs). You can then use :func:`isinstance` and :func:`issubclass` to check 679 683 whether 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`. 682 687 683 688 For Python, many of the advantages of interface specifications can be obtained … … 713 718 This type of bug commonly bites neophyte programmers. Consider this function:: 714 719 715 def foo( D={}): # Danger: shared reference to one dict for all calls720 def foo(mydict={}): # Danger: shared reference to one dict for all calls 716 721 ... compute something ... 717 D[key] = value718 return D719 720 The first time you call this function, `` D`` contains a single item. The second721 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 725 The first time you call this function, ``mydict`` contains a single item. The 726 second time, ``mydict`` contains two items because when ``foo()`` begins 727 executing, ``mydict`` starts out with an item already in it. 723 728 724 729 It is often expected that a function call creates new objects for default … … 736 741 list/dictionary/whatever if it is. For example, don't write:: 737 742 738 def foo( dict={}):743 def foo(mydict={}): 739 744 ... 740 745 741 746 but:: 742 747 743 def foo( dict=None):744 if dict is None:745 dict = {}# create a new dict for local namespace748 def foo(mydict=None): 749 if mydict is None: 750 mydict = {} # create a new dict for local namespace 746 751 747 752 This feature can be useful. When you have a function that's time-consuming to … … 751 756 752 757 # Callers will never provide a third parameter for this function. 753 def expensive 754 if _cache.has_key((arg1, arg2)):758 def expensive(arg1, arg2, _cache={}): 759 if (arg1, arg2) in _cache: 755 760 return _cache[(arg1, arg2)] 756 761 … … 772 777 languages. For example:: 773 778 774 class label: pass # declare a label779 class label: pass # declare a label 775 780 776 781 try: 777 782 ... 778 if (condition): raise label()# goto label783 if condition: raise label() # goto label 779 784 ... 780 except label: # where to goto785 except label: # where to goto 781 786 pass 782 787 ... … … 803 808 accept forward slashes too:: 804 809 805 f = open("/mydir/file.txt") # works fine!810 f = open("/mydir/file.txt") # works fine! 806 811 807 812 If you're trying to build a pathname for a DOS command, try e.g. one of :: … … 820 825 821 826 with obj: 822 a = 1 # equivalent to obj.a = 1827 a = 1 # equivalent to obj.a = 1 823 828 total = total + 1 # obj.total = obj.total + 1 824 829 … … 851 856 volume) can, however, easily be achieved in Python by assignment. Instead of:: 852 857 853 function(args). dict[index][index].a = 21854 function(args). dict[index][index].b = 42855 function(args). dict[index][index].c = 63858 function(args).mydict[index][index].a = 21 859 function(args).mydict[index][index].b = 42 860 function(args).mydict[index][index].c = 63 856 861 857 862 write this:: 858 863 859 ref = function(args). dict[index][index]864 ref = function(args).mydict[index][index] 860 865 ref.a = 21 861 866 ref.b = 42 … … 864 869 This also has the side-effect of increasing execution speed because name 865 870 bindings 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. 871 to perform the resolution once. 868 872 869 873 … … 908 912 When you have a literal value for a list, tuple, or dictionary spread across 909 913 multiple 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 in911 your editorwithout creating a syntax error.914 remember to add a comma to the previous line. The lines can also be reordered 915 without creating a syntax error. 912 916 913 917 Accidentally omitting the comma can lead to errors that are hard to diagnose.
Note:
See TracChangeset
for help on using the changeset viewer.