Skip to content

Commit 043d6f6

Browse files
committed
Copied doc for reload() from trunk's function.rst to imp.rst
1 parent 13a7a21 commit 043d6f6

File tree

20 files changed

+465
-48
lines changed

20 files changed

+465
-48
lines changed

Doc/library/collections.rst

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -489,7 +489,7 @@ three additional methods and one attribute.
489489
>>> Point._make(t)
490490
Point(x=11, y=22)
491491

492-
.. method:: somenamedtuple._asdict()
492+
.. method:: namedtuple._asdict()
493493

494494
Return a new dict which maps field names to their corresponding values:
495495

@@ -498,7 +498,7 @@ three additional methods and one attribute.
498498
>>> p._asdict()
499499
{'x': 11, 'y': 22}
500500
501-
.. method:: somenamedtuple._replace(kwargs)
501+
.. method:: namedtuple._replace(kwargs)
502502

503503
Return a new instance of the named tuple replacing specified fields with new values:
504504

@@ -511,7 +511,7 @@ three additional methods and one attribute.
511511
>>> for partnum, record in inventory.items():
512512
... inventory[partnum] = record._replace(price=newprices[partnum], updated=time.now())
513513

514-
.. attribute:: somenamedtuple._fields
514+
.. attribute:: namedtuple._fields
515515

516516
Tuple of strings listing the field names. This is useful for introspection
517517
and for creating new named tuple types from existing named tuples.
@@ -541,15 +541,28 @@ When casting a dictionary to a named tuple, use the double-star-operator [#]_::
541541
Point(x=11, y=22)
542542

543543
Since a named tuple is a regular Python class, it is easy to add or change
544-
functionality. For example, the display format can be changed by overriding
545-
the :meth:`__repr__` method:
546-
547-
::
548-
549-
>>> Point = namedtuple('Point', 'x y')
550-
>>> Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self
551-
>>> Point(x=11, y=22)
552-
Point(11.000, 22.000)
544+
functionality with a subclass. Here is how to add a calculated field and
545+
a fixed-width print format::
546+
547+
>>> class Point(namedtuple('Point', 'x y')):
548+
@property
549+
def hypot(self):
550+
return (self.x ** 2 + self.y ** 2) ** 0.5
551+
def __repr__(self):
552+
return 'Point(x=%.3f, y=%.3f, hypot=%.3f)' % (self.x, self.y, self.hypot)
553+
554+
>>> print Point(3, 4),'\n', Point(2, 5), '\n', Point(9./7, 6)
555+
Point(x=3.000, y=4.000, hypot=5.000)
556+
Point(x=2.000, y=5.000, hypot=5.385)
557+
Point(x=1.286, y=6.000, hypot=6.136)
558+
559+
Another use for subclassing is to replace performance critcal methods with
560+
faster versions that bypass error-checking and localize variable access::
561+
562+
>>> class Point(namedtuple('Point', 'x y')):
563+
_make = classmethod(tuple.__new__)
564+
def _replace(self, _map=map, **kwds):
565+
return self._make(_map(kwds.pop, ('x', 'y'), self))
553566

554567
Default values can be implemented by starting with a prototype instance
555568
and customizing it with :meth:`_replace`:

Doc/library/getopt.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ This module helps scripts to parse the command line arguments in ``sys.argv``.
1111
It supports the same conventions as the Unix :cfunc:`getopt` function (including
1212
the special meanings of arguments of the form '``-``' and '``--``'). Long
1313
options similar to those supported by GNU software may be used as well via an
14-
optional third argument. This module provides a single function and an
14+
optional third argument. This module provides two functions and an
1515
exception:
1616

1717

Doc/library/imp.rst

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,68 @@ This module provides an interface to the mechanisms used to implement the
123123
function does nothing.
124124

125125

126+
.. function:: reload(module)
127+
128+
Reload a previously imported *module*. The argument must be a module object, so
129+
it must have been successfully imported before. This is useful if you have
130+
edited the module source file using an external editor and want to try out the
131+
new version without leaving the Python interpreter. The return value is the
132+
module object (the same as the *module* argument).
133+
134+
When ``reload(module)`` is executed:
135+
136+
* Python modules' code is recompiled and the module-level code reexecuted,
137+
defining a new set of objects which are bound to names in the module's
138+
dictionary. The ``init`` function of extension modules is not called a second
139+
time.
140+
141+
* As with all other objects in Python the old objects are only reclaimed after
142+
their reference counts drop to zero.
143+
144+
* The names in the module namespace are updated to point to any new or changed
145+
objects.
146+
147+
* Other references to the old objects (such as names external to the module) are
148+
not rebound to refer to the new objects and must be updated in each namespace
149+
where they occur if that is desired.
150+
151+
There are a number of other caveats:
152+
153+
If a module is syntactically correct but its initialization fails, the first
154+
:keyword:`import` statement for it does not bind its name locally, but does
155+
store a (partially initialized) module object in ``sys.modules``. To reload the
156+
module you must first :keyword:`import` it again (this will bind the name to the
157+
partially initialized module object) before you can :func:`reload` it.
158+
159+
When a module is reloaded, its dictionary (containing the module's global
160+
variables) is retained. Redefinitions of names will override the old
161+
definitions, so this is generally not a problem. If the new version of a module
162+
does not define a name that was defined by the old version, the old definition
163+
remains. This feature can be used to the module's advantage if it maintains a
164+
global table or cache of objects --- with a :keyword:`try` statement it can test
165+
for the table's presence and skip its initialization if desired::
166+
167+
try:
168+
cache
169+
except NameError:
170+
cache = {}
171+
172+
It is legal though generally not very useful to reload built-in or dynamically
173+
loaded modules, except for :mod:`sys`, :mod:`__main__` and :mod:`__builtin__`.
174+
In many cases, however, extension modules are not designed to be initialized
175+
more than once, and may fail in arbitrary ways when reloaded.
176+
177+
If a module imports objects from another module using :keyword:`from` ...
178+
:keyword:`import` ..., calling :func:`reload` for the other module does not
179+
redefine the objects imported from it --- one way around this is to re-execute
180+
the :keyword:`from` statement, another is to use :keyword:`import` and qualified
181+
names (*module*.*name*) instead.
182+
183+
If a module instantiates instances of a class, reloading the module that defines
184+
the class does not affect the method definitions of the instances --- they
185+
continue to use the old class definition. The same is true for derived classes.
186+
187+
126188
The following constants with integer values, defined in this module, are used to
127189
indicate the search result of :func:`find_module`.
128190

Doc/library/logging.rst

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -688,7 +688,8 @@ functions.
688688

689689
Does basic configuration for the logging system by creating a
690690
:class:`StreamHandler` with a default :class:`Formatter` and adding it to the
691-
root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
691+
root logger. The function does nothing if any handlers have been defined for
692+
the root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
692693
:func:`error` and :func:`critical` will call :func:`basicConfig` automatically
693694
if no handlers are defined for the root logger.
694695

@@ -2384,24 +2385,24 @@ Here is the auxiliary module::
23842385

23852386
The output looks like this::
23862387

2387-
2005-03-23 23:47:11,663 - spam_application - INFO -
2388+
2005-03-23 23:47:11,663 - spam_application - INFO -
23882389
creating an instance of auxiliary_module.Auxiliary
2389-
2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
2390+
2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
23902391
creating an instance of Auxiliary
2391-
2005-03-23 23:47:11,665 - spam_application - INFO -
2392+
2005-03-23 23:47:11,665 - spam_application - INFO -
23922393
created an instance of auxiliary_module.Auxiliary
2393-
2005-03-23 23:47:11,668 - spam_application - INFO -
2394+
2005-03-23 23:47:11,668 - spam_application - INFO -
23942395
calling auxiliary_module.Auxiliary.do_something
2395-
2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
2396+
2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
23962397
doing something
2397-
2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
2398+
2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
23982399
done doing something
2399-
2005-03-23 23:47:11,670 - spam_application - INFO -
2400+
2005-03-23 23:47:11,670 - spam_application - INFO -
24002401
finished auxiliary_module.Auxiliary.do_something
2401-
2005-03-23 23:47:11,671 - spam_application - INFO -
2402+
2005-03-23 23:47:11,671 - spam_application - INFO -
24022403
calling auxiliary_module.some_function()
2403-
2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
2404+
2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
24042405
received a call to "some_function"
2405-
2005-03-23 23:47:11,673 - spam_application - INFO -
2406+
2005-03-23 23:47:11,673 - spam_application - INFO -
24062407
done with auxiliary_module.some_function()
24072408

Doc/library/socket.rst

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,27 @@ numeric address in *host* portion.
6565

6666
AF_NETLINK sockets are represented as pairs ``pid, groups``.
6767

68+
69+
Linux-only support for TIPC is also available using the :const:`AF_TIPC`
70+
address family. TIPC is an open, non-IP based networked protocol designed
71+
for use in clustered computer environments. Addresses are represented by a
72+
tuple, and the fields depend on the address type. The general tuple form is
73+
``(addr_type, v1, v2, v3 [, scope])``, where:
74+
75+
- *addr_type* is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, or
76+
TIPC_ADDR_ID.
77+
- *scope* is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and
78+
TIPC_NODE_SCOPE.
79+
- If *addr_type* is TIPC_ADDR_NAME, then *v1* is the server type, *v2* is
80+
the port identifier, and *v3* should be 0.
81+
82+
If *addr_type* is TIPC_ADDR_NAMESEQ, then *v1* is the server type, *v2*
83+
is the lower port number, and *v3* is the upper port number.
84+
85+
If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
86+
reference, and *v3* should be set to 0.
87+
88+
6889
All errors raise exceptions. The normal exceptions for invalid argument types
6990
and out-of-memory conditions can be raised; errors related to socket or address
7091
semantics raise the error :exc:`socket.error`.
@@ -162,6 +183,12 @@ The module :mod:`socket` exports the following constants and functions:
162183
:meth:`ioctl` method of socket objects.
163184

164185

186+
.. data:: TIPC_*
187+
188+
TIPC related constants, matching the ones exported by the C socket API. See
189+
the TIPC documentation for more information.
190+
191+
165192
.. data:: has_ipv6
166193

167194
This constant contains a boolean value which indicates if IPv6 is supported on

Doc/library/stdtypes.rst

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -389,9 +389,9 @@ This table lists the bit-string operations sorted in ascending priority
389389
| ``x & y`` | bitwise :dfn:`and` of *x* and | |
390390
| | *y* | |
391391
+------------+--------------------------------+----------+
392-
| ``x << n`` | *x* shifted left by *n* bits | (1), (2) |
392+
| ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
393393
+------------+--------------------------------+----------+
394-
| ``x >> n`` | *x* shifted right by *n* bits | (1), (3) |
394+
| ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
395395
+------------+--------------------------------+----------+
396396
| ``~x`` | the bits of *x* inverted | |
397397
+------------+--------------------------------+----------+
@@ -436,7 +436,7 @@ One method needs to be defined for container objects to provide iteration
436436
support:
437437

438438

439-
.. method:: container.__iter__()
439+
.. method:: object.__iter__()
440440

441441
Return an iterator object. The object is required to support the iterator
442442
protocol described below. If a container supports different types of
@@ -537,7 +537,7 @@ support slicing, concatenation or repetition, and using ``in``, ``not in``,
537537
Most sequence types support the following operations. The ``in`` and ``not in``
538538
operations have the same priorities as the comparison operations. The ``+`` and
539539
``*`` operations have the same priority as the corresponding numeric operations.
540-
[#]_
540+
[#]_ Additional methods are provided for :ref:`typesseq-mutable`.
541541

542542
This table lists the sequence operations sorted in ascending priority
543543
(operations in the same box have the same priority). In the table, *s* and *t*
@@ -560,9 +560,9 @@ are sequences of the same type; *n*, *i* and *j* are integers:
560560
+------------------+--------------------------------+----------+
561561
| ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
562562
+------------------+--------------------------------+----------+
563-
| ``s[i:j]`` | slice of *s* from *i* to *j* | (3), (4) |
563+
| ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
564564
+------------------+--------------------------------+----------+
565-
| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3), (5) |
565+
| ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
566566
| | with step *k* | |
567567
+------------------+--------------------------------+----------+
568568
| ``len(s)`` | length of *s* | |

Doc/tutorial/controlflow.rst

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -595,10 +595,57 @@ Here is an example of a multi-line docstring::
595595
No, really, it doesn't do anything.
596596

597597

598+
.. _tut-codingstyle:
599+
600+
Intermezzo: Coding Style
601+
========================
602+
603+
.. sectionauthor:: Georg Brandl <georg@python.org>
604+
.. index:: pair: coding; style
605+
606+
Now that you are about to write longer, more complex pieces of Python, it is a
607+
good time to talk about *coding style*. Most languages can be written (or more
608+
concise, *formatted*) in different styles; some are more readable than others.
609+
Making it easy for others to read your code is always a good idea, and adopting
610+
a nice coding style helps tremendously for that.
611+
612+
For Python, :pep:`8` has emerged as the style guide that most projects adher to;
613+
it promotes a very readable and eye-pleasing coding style. Every Python
614+
developer should read it at some point; here are the most important points
615+
extracted for you:
616+
617+
* Use 4-space indentation, and no tabs.
618+
619+
4 spaces are a good compromise between small indentation (allows greater
620+
nesting depth) and large indentation (easier to read). Tabs introduce
621+
confusion, and are best left out.
622+
623+
* Wrap lines so that they don't exceed 79 characters.
624+
625+
This helps users with small displays and makes it possible to have several
626+
code files side-by-side on larger displays.
627+
628+
* Use blank lines to separate functions and classes, and larger blocks of
629+
code inside functions.
630+
631+
* When possible, put comments on a line of their own.
632+
633+
* Use docstrings.
634+
635+
* Use spaces around operators and after commas, but not directly inside
636+
bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
637+
638+
* Name your classes and functions consistently; the convention is to use
639+
``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
640+
and methods. Always use ``self`` as the name for the first method argument.
641+
642+
* Don't use fancy encodings if your code is meant to be used in international
643+
environments. Plain ASCII works best in any case.
644+
598645

599646
.. rubric:: Footnotes
600647

601-
.. [#] Actually, *call by object reference* would be a better description, since if a
602-
mutable object is passed, the caller will see any changes the callee makes to it
603-
(items inserted into a list).
648+
.. [#] Actually, *call by object reference* would be a better description,
649+
since if a mutable object is passed, the caller will see any changes the
650+
callee makes to it (items inserted into a list).
604651

Doc/tutorial/introduction.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,7 @@ series as follows::
548548
... # the sum of two elements defines the next
549549
... a, b = 0, 1
550550
>>> while b < 10:
551-
... print(b)
551+
... print b
552552
... a, b = b, a+b
553553
...
554554
1

Lib/abc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ def __subclasscheck__(cls, subclass):
187187
cls._abc_negative_cache.add(subclass)
188188
return ok
189189
# Check if it's a direct subclass
190-
if cls in subclass.__mro__:
190+
if cls in getattr(subclass, '__mro__', ()):
191191
cls._abc_cache.add(subclass)
192192
return True
193193
# Check if it's a subclass of a registered class (recursive)

Lib/collections.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,9 @@ def namedtuple(typename, field_names, verbose=False):
6565
def __new__(cls, %(argtxt)s):
6666
return tuple.__new__(cls, (%(argtxt)s)) \n
6767
@classmethod
68-
def _make(cls, iterable):
68+
def _make(cls, iterable, new=tuple.__new__, len=len):
6969
'Make a new %(typename)s object from a sequence or iterable'
70-
result = tuple.__new__(cls, iterable)
70+
result = new(cls, iterable)
7171
if len(result) != %(numfields)d:
7272
raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
7373
return result \n
@@ -115,8 +115,22 @@ def _replace(self, **kwds):
115115
assert p == loads(dumps(p))
116116

117117
# test and demonstrate ability to override methods
118-
Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self
119-
print(p)
118+
class Point(namedtuple('Point', 'x y')):
119+
@property
120+
def hypot(self):
121+
return (self.x ** 2 + self.y ** 2) ** 0.5
122+
def __repr__(self):
123+
return 'Point(x=%.3f, y=%.3f, hypot=%.3f)' % (self.x, self.y, self.hypot)
124+
125+
print(Point(3, 4),'\n', Point(2, 5), '\n', Point(9./7, 6))
126+
127+
class Point(namedtuple('Point', 'x y')):
128+
'Point class with optimized _make() and _replace() without error-checking'
129+
_make = classmethod(tuple.__new__)
130+
def _replace(self, _map=map, **kwds):
131+
return self._make(_map(kwds.pop, ('x', 'y'), self))
132+
133+
print(Point(11, 22)._replace(x=100))
120134

121135
import doctest
122136
TestResults = namedtuple('TestResults', 'failed attempted')

0 commit comments

Comments
 (0)