@@ -25,8 +25,9 @@ Reference Manual <pdb>`. You can also write your own debugger by using the code
25
25
for pdb as an example.
26
26
27
27
The IDLE interactive development environment, which is part of the standard
28
- Python distribution (normally available as Tools/scripts/idle), includes a
29
- graphical debugger.
28
+ Python distribution (normally available as
29
+ `Tools/scripts/idle3 <https://github.com/python/cpython/blob/main/Tools/scripts/idle3 >`_),
30
+ includes a graphical debugger.
30
31
31
32
PythonWin is a Python IDE that includes a GUI debugger based on pdb. The
32
33
PythonWin debugger colors breakpoints and has quite a few cool features such as
@@ -78,7 +79,8 @@ set of modules required by a program and bind these modules together with a
78
79
Python binary to produce a single executable.
79
80
80
81
One is to use the freeze tool, which is included in the Python source tree as
81
- ``Tools/freeze ``. It converts Python byte code to C arrays; with a C compiler you can
82
+ `Tools/freeze <https://github.com/python/cpython/tree/main/Tools/freeze >`_.
83
+ It converts Python byte code to C arrays; with a C compiler you can
82
84
embed all your modules into a new program, which is then linked with the
83
85
standard Python modules.
84
86
@@ -114,7 +116,7 @@ Core Language
114
116
Why am I getting an UnboundLocalError when the variable has a value?
115
117
--------------------------------------------------------------------
116
118
117
- It can be a surprise to get the UnboundLocalError in previously working
119
+ It can be a surprise to get the :exc: ` UnboundLocalError ` in previously working
118
120
code when it is modified by adding an assignment statement somewhere in
119
121
the body of a function.
120
122
@@ -123,6 +125,7 @@ This code:
123
125
>>> x = 10
124
126
>>> def bar ():
125
127
... print (x)
128
+ ...
126
129
>>> bar()
127
130
10
128
131
@@ -133,7 +136,7 @@ works, but this code:
133
136
... print (x)
134
137
... x += 1
135
138
136
- results in an UnboundLocalError:
139
+ results in an :exc: ` ! UnboundLocalError` :
137
140
138
141
>>> foo()
139
142
Traceback (most recent call last):
@@ -155,6 +158,7 @@ global:
155
158
... global x
156
159
... print (x)
157
160
... x += 1
161
+ ...
158
162
>>> foobar()
159
163
10
160
164
@@ -176,6 +180,7 @@ keyword:
176
180
... x += 1
177
181
... bar()
178
182
... print (x)
183
+ ...
179
184
>>> foo()
180
185
10
181
186
11
@@ -273,7 +278,7 @@ main.py::
273
278
import mod
274
279
print(config.x)
275
280
276
- Note that using a module is also the basis for implementing the Singleton design
281
+ Note that using a module is also the basis for implementing the singleton design
277
282
pattern, for the same reason.
278
283
279
284
@@ -291,9 +296,9 @@ using multiple imports per line uses less screen space.
291
296
292
297
It's good practice if you import modules in the following order:
293
298
294
- 1. standard library modules -- e.g. `` sys ``, `` os ``, `` getopt ``, `` re ` `
299
+ 1. standard library modules -- e.g. :mod: ` sys `, :mod: ` os `, :mod: ` argparse `, :mod: ` re `
295
300
2. third-party library modules (anything installed in Python's site-packages
296
- directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
301
+ directory) -- e.g. :mod: ` !dateutil `, :mod: ` !requests `, :mod: ` ! PIL.Image`
297
302
3. locally developed modules
298
303
299
304
It is sometimes necessary to move imports to a function or class to avoid
@@ -471,7 +476,7 @@ object ``x`` refers to). After this assignment we have two objects (the ints
471
476
472
477
Some operations (for example ``y.append(10) `` and ``y.sort() ``) mutate the
473
478
object, whereas superficially similar operations (for example ``y = y + [10] ``
474
- and `` sorted(y) ` `) create a new object. In general in Python (and in all cases
479
+ and :func: ` sorted(y) <sorted> `) create a new object. In general in Python (and in all cases
475
480
in the standard library) a method that mutates an object will return ``None ``
476
481
to help avoid getting the two types of operations confused. So if you
477
482
mistakenly write ``y.sort() `` thinking it will give you a sorted copy of ``y ``,
@@ -644,7 +649,7 @@ Sequences can be copied by slicing::
644
649
How can I find the methods or attributes of an object?
645
650
------------------------------------------------------
646
651
647
- For an instance x of a user-defined class, `` dir(x) ` ` returns an alphabetized
652
+ For an instance `` x `` of a user-defined class, :func: ` dir(x) <dir> ` returns an alphabetized
648
653
list of the names containing the instance attributes and methods and attributes
649
654
defined by its class.
650
655
@@ -669,9 +674,9 @@ callable. Consider the following code::
669
674
<__main__.A object at 0x16D07CC>
670
675
671
676
Arguably the class has a name: even though it is bound to two names and invoked
672
- through the name B the created instance is still reported as an instance of
673
- class A . However, it is impossible to say whether the instance's name is a or
674
- b , since both names are bound to the same value.
677
+ through the name `` B `` the created instance is still reported as an instance of
678
+ class `` A `` . However, it is impossible to say whether the instance's name is `` a `` or
679
+ `` b `` , since both names are bound to the same value.
675
680
676
681
Generally speaking it should not be necessary for your code to "know the names"
677
682
of particular values. Unless you are deliberately writing introspective
@@ -841,7 +846,7 @@ How do I get int literal attribute instead of SyntaxError?
841
846
----------------------------------------------------------
842
847
843
848
Trying to lookup an ``int `` literal attribute in the normal manner gives
844
- a syntax error because the period is seen as a decimal point::
849
+ a :exc: ` SyntaxError ` because the period is seen as a decimal point::
845
850
846
851
>>> 1.__class__
847
852
File "<stdin>", line 1
@@ -887,7 +892,7 @@ leading '0' in a decimal number (except '0').
887
892
How do I convert a number to a string?
888
893
--------------------------------------
889
894
890
- To convert, e.g., the number 144 to the string '144', use the built-in type
895
+ To convert, e.g., the number `` 144 `` to the string `` '144' `` , use the built-in type
891
896
constructor :func: `str `. If you want a hexadecimal or octal representation, use
892
897
the built-in functions :func: `hex ` or :func: `oct `. For fancy formatting, see
893
898
the :ref: `f-strings ` and :ref: `formatstrings ` sections,
@@ -1006,11 +1011,11 @@ Not as such.
1006
1011
For simple input parsing, the easiest approach is usually to split the line into
1007
1012
whitespace-delimited words using the :meth: `~str.split ` method of string objects
1008
1013
and then convert decimal strings to numeric values using :func: `int ` or
1009
- :func: `float `. `` split() ` ` supports an optional "sep" parameter which is useful
1014
+ :func: `float `. :meth: ` ! split() ` supports an optional "sep" parameter which is useful
1010
1015
if the line uses something other than whitespace as a separator.
1011
1016
1012
1017
For more complicated input parsing, regular expressions are more powerful
1013
- than C's :c:func: ` sscanf ` and better suited for the task.
1018
+ than C's `` sscanf ` ` and better suited for the task.
1014
1019
1015
1020
1016
1021
What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?
@@ -1206,15 +1211,16 @@ difference is that a Python list can contain objects of many different types.
1206
1211
1207
1212
The ``array `` module also provides methods for creating arrays of fixed types
1208
1213
with compact representations, but they are slower to index than lists. Also
1209
- note that NumPy and other third party packages define array-like structures with
1214
+ note that `NumPy <https://numpy.org/ >`_
1215
+ and other third party packages define array-like structures with
1210
1216
various characteristics as well.
1211
1217
1212
- To get Lisp-style linked lists, you can emulate cons cells using tuples::
1218
+ To get Lisp-style linked lists, you can emulate * cons cells * using tuples::
1213
1219
1214
1220
lisp_list = ("like", ("this", ("example", None) ) )
1215
1221
1216
1222
If mutability is desired, you could use lists instead of tuples. Here the
1217
- analogue of lisp car is ``lisp_list[0] `` and the analogue of cdr is
1223
+ analogue of a Lisp * car * is ``lisp_list[0] `` and the analogue of * cdr * is
1218
1224
``lisp_list[1] ``. Only do this if you're sure you really need to, because it's
1219
1225
usually a lot slower than using Python lists.
1220
1226
@@ -1334,11 +1340,12 @@ that even though there was an error, the append worked::
1334
1340
['foo', 'item']
1335
1341
1336
1342
To see why this happens, you need to know that (a) if an object implements an
1337
- ``__iadd__ `` magic method, it gets called when the ``+= `` augmented assignment
1343
+ :meth: `~object.__iadd__ ` magic method, it gets called when the ``+= `` augmented
1344
+ assignment
1338
1345
is executed, and its return value is what gets used in the assignment statement;
1339
- and (b) for lists, `` __iadd__ `` is equivalent to calling `` extend ` ` on the list
1346
+ and (b) for lists, :meth: ` ! __iadd__ ` is equivalent to calling :meth: ` ~list. extend ` on the list
1340
1347
and returning the list. That's why we say that for lists, ``+= `` is a
1341
- "shorthand" for `` list.extend ` `::
1348
+ "shorthand" for :meth: ` ! list.extend `::
1342
1349
1343
1350
>>> a_list = []
1344
1351
>>> a_list += [1]
@@ -1363,7 +1370,7 @@ Thus, in our tuple example what is happening is equivalent to::
1363
1370
...
1364
1371
TypeError: 'tuple' object does not support item assignment
1365
1372
1366
- The `` __iadd__ ` ` succeeds, and thus the list is extended, but even though
1373
+ The :meth: ` ! __iadd__ ` succeeds, and thus the list is extended, but even though
1367
1374
``result `` points to the same object that ``a_tuple[0] `` already points to,
1368
1375
that final assignment still results in an error, because tuples are immutable.
1369
1376
@@ -1440,7 +1447,8 @@ See also :ref:`why-self`.
1440
1447
How do I check if an object is an instance of a given class or of a subclass of it?
1441
1448
-----------------------------------------------------------------------------------
1442
1449
1443
- Use the built-in function ``isinstance(obj, cls) ``. You can check if an object
1450
+ Use the built-in function :func: `isinstance(obj, cls) <isinstance> `. You can
1451
+ check if an object
1444
1452
is an instance of any of a number of classes by providing a tuple instead of a
1445
1453
single class, e.g. ``isinstance(obj, (class1, class2, ...)) ``, and can also
1446
1454
check whether an object is one of Python's built-in types, e.g.
@@ -1537,21 +1545,22 @@ Here the ``UpperOut`` class redefines the ``write()`` method to convert the
1537
1545
argument string to uppercase before calling the underlying
1538
1546
``self._outfile.write() `` method. All other methods are delegated to the
1539
1547
underlying ``self._outfile `` object. The delegation is accomplished via the
1540
- `` __getattr__ ` ` method; consult :ref: `the language reference <attribute-access >`
1548
+ :meth: ` ~object. __getattr__ ` method; consult :ref: `the language reference <attribute-access >`
1541
1549
for more information about controlling attribute access.
1542
1550
1543
1551
Note that for more general cases delegation can get trickier. When attributes
1544
- must be set as well as retrieved, the class must define a :meth: `__setattr__ `
1552
+ must be set as well as retrieved, the class must define a :meth: `~object. __setattr__ `
1545
1553
method too, and it must do so carefully. The basic implementation of
1546
- :meth: `__setattr__ ` is roughly equivalent to the following::
1554
+ :meth: `! __setattr__ ` is roughly equivalent to the following::
1547
1555
1548
1556
class X:
1549
1557
...
1550
1558
def __setattr__(self, name, value):
1551
1559
self.__dict__[name] = value
1552
1560
...
1553
1561
1554
- Most :meth: `__setattr__ ` implementations must modify ``self.__dict__ `` to store
1562
+ Most :meth: `!__setattr__ ` implementations must modify
1563
+ :meth: `self.__dict__ <object.__dict__> ` to store
1555
1564
local state for self without causing an infinite recursion.
1556
1565
1557
1566
@@ -1689,25 +1698,25 @@ My class defines __del__ but it is not called when I delete the object.
1689
1698
1690
1699
There are several possible reasons for this.
1691
1700
1692
- The del statement does not necessarily call :meth: `__del__ ` -- it simply
1701
+ The :keyword: ` del ` statement does not necessarily call :meth: `~object. __del__ ` -- it simply
1693
1702
decrements the object's reference count, and if this reaches zero
1694
- :meth: `__del__ ` is called.
1703
+ :meth: `! __del__ ` is called.
1695
1704
1696
1705
If your data structures contain circular links (e.g. a tree where each child has
1697
1706
a parent reference and each parent has a list of children) the reference counts
1698
1707
will never go back to zero. Once in a while Python runs an algorithm to detect
1699
1708
such cycles, but the garbage collector might run some time after the last
1700
- reference to your data structure vanishes, so your :meth: `__del__ ` method may be
1709
+ reference to your data structure vanishes, so your :meth: `! __del__ ` method may be
1701
1710
called at an inconvenient and random time. This is inconvenient if you're trying
1702
- to reproduce a problem. Worse, the order in which object's :meth: `__del__ `
1711
+ to reproduce a problem. Worse, the order in which object's :meth: `! __del__ `
1703
1712
methods are executed is arbitrary. You can run :func: `gc.collect ` to force a
1704
1713
collection, but there *are * pathological cases where objects will never be
1705
1714
collected.
1706
1715
1707
1716
Despite the cycle collector, it's still a good idea to define an explicit
1708
1717
``close() `` method on objects to be called whenever you're done with them. The
1709
1718
``close() `` method can then remove attributes that refer to subobjects. Don't
1710
- call :meth: `__del__ ` directly -- :meth: `__del__ ` should call ``close() `` and
1719
+ call :meth: `! __del__ ` directly -- :meth: `! __del__ ` should call ``close() `` and
1711
1720
``close() `` should make sure that it can be called more than once for the same
1712
1721
object.
1713
1722
@@ -1724,7 +1733,7 @@ and sibling references (if they need them!).
1724
1733
Normally, calling :func:`sys.exc_clear` will take care of this by clearing
1725
1734
the last recorded exception.
1726
1735
1727
- Finally, if your :meth: `__del__ ` method raises an exception, a warning message
1736
+ Finally, if your :meth: `! __del__ ` method raises an exception, a warning message
1728
1737
is printed to :data: `sys.stderr `.
1729
1738
1730
1739
@@ -1852,8 +1861,8 @@ For example, here is the implementation of
1852
1861
How can a subclass control what data is stored in an immutable instance?
1853
1862
------------------------------------------------------------------------
1854
1863
1855
- When subclassing an immutable type, override the :meth: `__new__ ` method
1856
- instead of the :meth: `__init__ ` method. The latter only runs *after * an
1864
+ When subclassing an immutable type, override the :meth: `~object. __new__ ` method
1865
+ instead of the :meth: `~object. __init__ ` method. The latter only runs *after * an
1857
1866
instance is created, which is too late to alter data in an immutable
1858
1867
instance.
1859
1868
@@ -1955,8 +1964,8 @@ can't be made to work because it cannot detect changes to the
1955
1964
attributes.
1956
1965
1957
1966
To make the *lru_cache * approach work when the *station_id * is mutable,
1958
- the class needs to define the * __eq__ * and * __hash__ * methods so that
1959
- the cache can detect relevant attribute updates::
1967
+ the class needs to define the :meth: ` ~object. __eq__` and :meth: ` ~object. __hash__`
1968
+ methods so that the cache can detect relevant attribute updates::
1960
1969
1961
1970
class Weather:
1962
1971
"Example with a mutable station identifier"
0 commit comments