Skip to content

Commit 0633095

Browse files
author
Erlend E. Aasland
committed
Sync with 'main' bco. pythonGH-27884
2 parents fe0fd6f + 3df0fc8 commit 0633095

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+2161
-389
lines changed

Doc/c-api/exceptions.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ For convenience, some of these functions will always return a
100100
This is the most common way to set the error indicator. The first argument
101101
specifies the exception type; it is normally one of the standard exceptions,
102102
e.g. :c:data:`PyExc_RuntimeError`. You need not increment its reference count.
103-
The second argument is an error message; it is decoded from ``'utf-8``'.
103+
The second argument is an error message; it is decoded from ``'utf-8'``.
104104
105105
106106
.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value)

Doc/faq/programming.rst

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1826,6 +1826,55 @@ For example, here is the implementation of
18261826
return True
18271827
return False
18281828

1829+
1830+
How can a subclass control what data is stored in an immutable instance?
1831+
------------------------------------------------------------------------
1832+
1833+
When subclassing an immutable type, override the :meth:`__new__` method
1834+
instead of the :meth:`__init__` method. The latter only runs *after* an
1835+
instance is created, which is too late to alter data in an immutable
1836+
instance.
1837+
1838+
All of these immutable classes have a different signature than their
1839+
parent class:
1840+
1841+
.. testcode::
1842+
1843+
from datetime import date
1844+
1845+
class FirstOfMonthDate(date):
1846+
"Always choose the first day of the month"
1847+
def __new__(cls, year, month, day):
1848+
return super().__new__(cls, year, month, 1)
1849+
1850+
class NamedInt(int):
1851+
"Allow text names for some numbers"
1852+
xlat = {'zero': 0, 'one': 1, 'ten': 10}
1853+
def __new__(cls, value):
1854+
value = cls.xlat.get(value, value)
1855+
return super().__new__(cls, value)
1856+
1857+
class TitleStr(str):
1858+
"Convert str to name suitable for a URL path"
1859+
def __new__(cls, s):
1860+
s = s.lower().replace(' ', '-')
1861+
s = ''.join([c for c in s if c.isalnum() or c == '-'])
1862+
return super().__new__(cls, s)
1863+
1864+
The classes can be used like this:
1865+
1866+
.. doctest::
1867+
1868+
>>> FirstOfMonthDate(2012, 2, 14)
1869+
FirstOfMonthDate(2012, 2, 1)
1870+
>>> NamedInt('ten')
1871+
10
1872+
>>> NamedInt(20)
1873+
20
1874+
>>> TitleStr('Blog: Why Python Rocks')
1875+
'blog-why-python-rocks'
1876+
1877+
18291878
How do I cache method calls?
18301879
----------------------------
18311880

0 commit comments

Comments
 (0)