Skip to content

Commit 4ae65a0

Browse files
author
Erlend E. Aasland
committed
Merge remote-tracking branch 'upstream/main' into sqlite-threadsafety
2 parents 4d8baff + 7401694 commit 4ae65a0

Some content is hidden

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

50 files changed

+943
-238
lines changed

.github/workflows/posix-deps-apt.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ apt-get update
33

44
apt-get -yq install \
55
build-essential \
6+
pkg-config \
67
ccache \
78
gdb \
89
lcov \

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ Tools/unicode/data/
120120
Tools/msi/obj
121121
Tools/ssl/amd64
122122
Tools/ssl/win32
123+
Tools/freeze/test/outdir
123124

124125
# The frozen modules are always generated by the build so we don't
125126
# keep them in the repo. Also see Tools/scripts/freeze_modules.py.

Doc/c-api/gcsupport.rst

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,14 @@ Constructors for container types must conform to two rules:
3333
#. Once all the fields which may contain references to other containers are
3434
initialized, it must call :c:func:`PyObject_GC_Track`.
3535

36+
Similarly, the deallocator for the object must conform to a similar pair of
37+
rules:
38+
39+
#. Before fields which refer to other containers are invalidated,
40+
:c:func:`PyObject_GC_UnTrack` must be called.
41+
42+
#. The object's memory must be deallocated using :c:func:`PyObject_GC_Del`.
43+
3644
.. warning::
3745
If a type adds the Py_TPFLAGS_HAVE_GC, then it *must* implement at least
3846
a :c:member:`~PyTypeObject.tp_traverse` handler or explicitly use one
@@ -100,14 +108,6 @@ Constructors for container types must conform to two rules:
100108
101109
.. versionadded:: 3.9
102110
103-
Similarly, the deallocator for the object must conform to a similar pair of
104-
rules:
105-
106-
#. Before fields which refer to other containers are invalidated,
107-
:c:func:`PyObject_GC_UnTrack` must be called.
108-
109-
#. The object's memory must be deallocated using :c:func:`PyObject_GC_Del`.
110-
111111
112112
.. c:function:: void PyObject_GC_Del(void *op)
113113

Doc/c-api/typeobj.rst

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,18 @@ and :c:type:`PyType_Type` effectively act as defaults.)
668668
:c:func:`PyObject_GC_Del` if the instance was allocated using
669669
:c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`.
670670

671+
If the type supports garbage collection (has the :const:`Py_TPFLAGS_HAVE_GC`
672+
flag bit set), the destructor should call :c:func:`PyObject_GC_UnTrack`
673+
before clearing any member fields.
674+
675+
.. code-block:: c
676+
677+
static void foo_dealloc(foo_object *self) {
678+
PyObject_GC_UnTrack(self);
679+
Py_CLEAR(self->ref);
680+
Py_TYPE(self)->tp_free((PyObject *)self);
681+
}
682+
671683
Finally, if the type is heap allocated (:const:`Py_TPFLAGS_HEAPTYPE`), the
672684
deallocator should decrement the reference count for its type object after
673685
calling the type deallocator. In order to avoid dangling pointers, the

Doc/extending/newtypes.rst

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,19 @@ function::
7373
newdatatype_dealloc(newdatatypeobject *obj)
7474
{
7575
free(obj->obj_UnderlyingDatatypePtr);
76-
Py_TYPE(obj)->tp_free(obj);
76+
Py_TYPE(obj)->tp_free((PyObject *)obj);
77+
}
78+
79+
If your type supports garbage collection, the destructor should call
80+
:c:func:`PyObject_GC_UnTrack` before clearing any member fields::
81+
82+
static void
83+
newdatatype_dealloc(newdatatypeobject *obj)
84+
{
85+
PyObject_GC_UnTrack(obj);
86+
Py_CLEAR(obj->other_obj);
87+
...
88+
Py_TYPE(obj)->tp_free((PyObject *)obj);
7789
}
7890

7991
.. index::

Doc/library/collections.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -343,7 +343,7 @@ All of those tests treat missing elements as having zero counts so that
343343
``Counter(a=1) == Counter(a=1, b=0)`` returns true.
344344

345345
.. versionadded:: 3.10
346-
Rich comparison operations we were added
346+
Rich comparison operations were added.
347347

348348
.. versionchanged:: 3.10
349349
In equality tests, missing elements are treated as having zero counts.

Doc/library/multiprocessing.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2636,12 +2636,13 @@ handler type) for messages from different processes to get mixed up.
26362636
inherited.
26372637

26382638
.. currentmodule:: multiprocessing
2639-
.. function:: log_to_stderr()
2639+
.. function:: log_to_stderr(level=None)
26402640

26412641
This function performs a call to :func:`get_logger` but in addition to
26422642
returning the logger created by get_logger, it adds a handler which sends
26432643
output to :data:`sys.stderr` using format
26442644
``'[%(levelname)s/%(processName)s] %(message)s'``.
2645+
You can modify ``levelname`` of the logger by passing a ``level`` argument.
26452646

26462647
Below is an example session with logging turned on::
26472648

Doc/library/sqlite3.rst

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,24 @@ Module functions and constants
117117
------------------------------
118118

119119

120+
.. data:: apilevel
121+
122+
String constant stating the supported DB-API level. Required by the DB-API.
123+
Hard-coded to ``"2.0"``.
124+
125+
.. data:: paramstyle
126+
127+
String constant stating the type of parameter marker formatting expected by
128+
the :mod:`sqlite3` module. Required by the DB-API. Hard-coded to
129+
``"qmark"``.
130+
131+
.. note::
132+
133+
The :mod:`sqlite3` module supports both ``qmark`` and ``numeric`` DB-API
134+
parameter styles, because that is what the underlying SQLite library
135+
supports. However, the DB-API does not allow multiple values for
136+
the ``paramstyle`` attribute.
137+
120138
.. data:: version
121139

122140
The version number of this module, as a string. This is not the version of
@@ -139,6 +157,26 @@ Module functions and constants
139157
The version number of the run-time SQLite library, as a tuple of integers.
140158

141159

160+
.. data:: threadsafety
161+
162+
Integer constant required by the DB-API, stating the level of thread safety
163+
the :mod:`sqlite3` module supports. Currently hard-coded to ``1``, meaning
164+
*"Threads may share the module, but not connections."* However, this may not
165+
always be true. You can check the underlying SQLite library's compile-time
166+
threaded mode using the following query::
167+
168+
import sqlite3
169+
con = sqlite3.connect(":memory:")
170+
con.execute("""
171+
select * from pragma_compile_options
172+
where compile_options like 'THREADSAFE=%'
173+
""").fetchall()
174+
175+
Note that the `SQLITE_THREADSAFE levels
176+
<https://sqlite.org/compile.html#threadsafe>`_ do not match the DB-API 2.0
177+
``threadsafety`` levels.
178+
179+
142180
.. data:: PARSE_DECLTYPES
143181

144182
This constant is meant to be used with the *detect_types* parameter of the
@@ -710,6 +748,14 @@ Cursor Objects
710748
The cursor will be unusable from this point forward; a :exc:`ProgrammingError`
711749
exception will be raised if any operation is attempted with the cursor.
712750

751+
.. method:: setinputsizes(sizes)
752+
753+
Required by the DB-API. Is a no-op in :mod:`sqlite3`.
754+
755+
.. method:: setoutputsize(size [, column])
756+
757+
Required by the DB-API. Is a no-op in :mod:`sqlite3`.
758+
713759
.. attribute:: rowcount
714760

715761
Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this

Doc/library/typing.rst

Lines changed: 41 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,11 @@
1717

1818
--------------
1919

20-
This module provides runtime support for type hints as specified by
21-
:pep:`484`, :pep:`526`, :pep:`544`, :pep:`586`, :pep:`589`, :pep:`591`,
22-
:pep:`593`, :pep:`612`, :pep:`613` and :pep:`647`.
23-
The most fundamental support consists of the types :data:`Any`, :data:`Union`,
24-
:data:`Tuple`, :data:`Callable`, :class:`TypeVar`, and
25-
:class:`Generic`. For full specification please see :pep:`484`. For
26-
a simplified introduction to type hints see :pep:`483`.
20+
This module provides runtime support for type hints. The most fundamental
21+
support consists of the types :data:`Any`, :data:`Union`, :data:`Tuple`,
22+
:data:`Callable`, :class:`TypeVar`, and :class:`Generic`. For a full
23+
specification, please see :pep:`484`. For a simplified introduction to type
24+
hints, see :pep:`483`.
2725

2826

2927
The function below takes and returns a string and is annotated as follows::
@@ -35,6 +33,42 @@ In the function ``greeting``, the argument ``name`` is expected to be of type
3533
:class:`str` and the return type :class:`str`. Subtypes are accepted as
3634
arguments.
3735

36+
.. _relevant-peps:
37+
38+
Relevant PEPs
39+
=============
40+
41+
Since the initial introduction of type hints in :pep:`484` and :pep:`483`, a
42+
number of PEPs have modified and enhanced Python's framework for type
43+
annotations. These include:
44+
45+
* :pep:`526`: Syntax for Variable Annotations
46+
*Introducing* syntax for annotating variables outside of function
47+
definitions, and :data:`ClassVar`
48+
* :pep:`544`: Protocols: Structural subtyping (static duck typing)
49+
*Introducing* :class:`Protocol` and the
50+
:func:`@runtime_checkable<runtime_checkable>` decorator
51+
* :pep:`585`: Type Hinting Generics In Standard Collections
52+
*Introducing* the ability to use builtin collections and ABCs as
53+
:term:`generic types<generic type>`
54+
* :pep:`586`: Literal Types
55+
*Introducing* :data:`Literal`
56+
* :pep:`589`: TypedDict: Type Hints for Dictionaries with a Fixed Set of Keys
57+
*Introducing* :class:`TypedDict`
58+
* :pep:`591`: Adding a final qualifier to typing
59+
*Introducing* :data:`Final` and the :func:`@final<final>` decorator
60+
* :pep:`593`: Flexible function and variable annotations
61+
*Introducing* :data:`Annotated`
62+
* :pep:`604`: Allow writing union types as ``X | Y``
63+
*Introducing* :data:`types.UnionType` and the ability to use
64+
the binary-or operator ``|`` as syntactic sugar for a union of types
65+
* :pep:`612`: Parameter Specification Variables
66+
*Introducing* :class:`ParamSpec` and :data:`Concatenate`
67+
* :pep:`613`: Explicit Type Aliases
68+
*Introducing* :data:`TypeAlias`
69+
* :pep:`647`: User-Defined Type Guards
70+
*Introducing* :data:`TypeGuard`
71+
3872
.. _type-aliases:
3973

4074
Type aliases

Doc/reference/datamodel.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2577,8 +2577,8 @@ left undefined.
25772577
return the value of the object truncated to an :class:`~numbers.Integral`
25782578
(typically an :class:`int`).
25792579

2580-
If :meth:`__int__` is not defined then the built-in function :func:`int`
2581-
falls back to :meth:`__trunc__`.
2580+
The built-in function :func:`int` falls back to :meth:`__trunc__` if neither
2581+
:meth:`__int__` nor :meth:`__index__` is defined.
25822582

25832583

25842584
.. _context-managers:

Include/cpython/pystate.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ typedef struct _cframe {
4646
* accessed outside of their lifetime.
4747
*/
4848
int use_tracing;
49+
/* Pointer to the currently executing frame (it can be NULL) */
50+
struct _interpreter_frame *current_frame;
4951
struct _cframe *previous;
5052
} CFrame;
5153

@@ -77,8 +79,6 @@ struct _ts {
7779
struct _ts *next;
7880
PyInterpreterState *interp;
7981

80-
/* Borrowed reference to the current frame (it can be NULL) */
81-
struct _interpreter_frame *frame;
8282
int recursion_depth;
8383
int recursion_headroom; /* Allow 50 more calls to handle any errors. */
8484
int stackcheck_counter;

Include/internal/pycore_frame.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,21 @@ _PyFrame_LocalsToFast(InterpreterFrame *frame, int clear);
152152
InterpreterFrame *_PyThreadState_PushFrame(
153153
PyThreadState *tstate, PyFrameConstructor *con, PyObject *locals);
154154

155+
extern InterpreterFrame *
156+
_PyThreadState_BumpFramePointerSlow(PyThreadState *tstate, size_t size);
157+
158+
static inline InterpreterFrame *
159+
_PyThreadState_BumpFramePointer(PyThreadState *tstate, size_t size)
160+
{
161+
PyObject **base = tstate->datastack_top;
162+
PyObject **top = base + size;
163+
if (top < tstate->datastack_limit) {
164+
tstate->datastack_top = top;
165+
return (InterpreterFrame *)base;
166+
}
167+
return _PyThreadState_BumpFramePointerSlow(tstate, size);
168+
}
169+
155170
void _PyThreadState_PopFrame(PyThreadState *tstate, InterpreterFrame *frame);
156171

157172
#ifdef __cplusplus

Include/internal/pycore_interp.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,7 @@ struct _is {
335335
The integers that are preallocated are those in the range
336336
-_PY_NSMALLNEGINTS (inclusive) to _PY_NSMALLPOSINTS (not inclusive).
337337
*/
338-
PyLongObject* small_ints[_PY_NSMALLNEGINTS + _PY_NSMALLPOSINTS];
338+
PyLongObject small_ints[_PY_NSMALLNEGINTS + _PY_NSMALLPOSINTS];
339339
struct _Py_bytes_state bytes;
340340
struct _Py_unicode_state unicode;
341341
struct _Py_float_state float_state;

Include/internal/pycore_long.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ static inline PyObject* __PyLong_GetSmallInt_internal(int value)
1717
PyInterpreterState *interp = _PyInterpreterState_GET();
1818
assert(-_PY_NSMALLNEGINTS <= value && value < _PY_NSMALLPOSINTS);
1919
size_t index = _PY_NSMALLNEGINTS + value;
20-
PyObject *obj = (PyObject*)interp->small_ints[index];
20+
PyObject *obj = (PyObject*)&interp->small_ints[index];
2121
// _PyLong_GetZero(), _PyLong_GetOne() and get_small_int() must not be
2222
// called before _PyLong_Init() nor after _PyLong_Fini().
2323
assert(obj != NULL);

Include/internal/pycore_pylifecycle.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ extern PyStatus _PyUnicode_Init(PyInterpreterState *interp);
5353
extern PyStatus _PyUnicode_InitTypes(void);
5454
extern PyStatus _PyBytes_Init(PyInterpreterState *interp);
5555
extern int _PyStructSequence_Init(void);
56-
extern int _PyLong_Init(PyInterpreterState *interp);
56+
extern void _PyLong_Init(PyInterpreterState *interp);
5757
extern int _PyLong_InitTypes(void);
5858
extern PyStatus _PyTuple_Init(PyInterpreterState *interp);
5959
extern PyStatus _PyFaulthandler_Init(int enable);

Lib/doctest.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1034,10 +1034,8 @@ def _find(self, tests, obj, name, module, source_lines, globs, seen):
10341034
if inspect.isclass(obj) and self._recurse:
10351035
for valname, val in obj.__dict__.items():
10361036
# Special handling for staticmethod/classmethod.
1037-
if isinstance(val, staticmethod):
1038-
val = getattr(obj, valname)
1039-
if isinstance(val, classmethod):
1040-
val = getattr(obj, valname).__func__
1037+
if isinstance(val, (staticmethod, classmethod)):
1038+
val = val.__func__
10411039

10421040
# Recurse to methods, properties, and nested classes.
10431041
if ((inspect.isroutine(val) or inspect.isclass(val) or

Lib/inspect.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1325,6 +1325,8 @@ def getargvalues(frame):
13251325
def formatannotation(annotation, base_module=None):
13261326
if getattr(annotation, '__module__', None) == 'typing':
13271327
return repr(annotation).replace('typing.', '')
1328+
if isinstance(annotation, types.GenericAlias):
1329+
return str(annotation)
13281330
if isinstance(annotation, type):
13291331
if annotation.__module__ in ('builtins', base_module):
13301332
return annotation.__qualname__

Lib/sqlite3/__init__.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,40 @@
2020
# misrepresented as being the original software.
2121
# 3. This notice may not be removed or altered from any source distribution.
2222

23+
"""
24+
The sqlite3 extension module provides a DB-API 2.0 (PEP 249) compilant
25+
interface to the SQLite library, and requires SQLite 3.7.15 or newer.
26+
27+
To use the module, you must first create a database Connection object:
28+
29+
import sqlite3
30+
cx = sqlite3.connect("test.db") # test.db will be created or opened
31+
32+
You can also use the special database name ":memory:" to connect to a transient
33+
in-memory database:
34+
35+
cx = sqlite3.connect(":memory:") # connect to a database in RAM
36+
37+
Once you have a Connection object, you can create a Cursor object and call its
38+
execute() method to perform SQL queries:
39+
40+
cu = cx.cursor()
41+
42+
# create a table
43+
cu.execute("create table lang(name, first_appeared)")
44+
45+
# insert values into a table
46+
cu.execute("insert into lang values (?, ?)", ("C", 1972))
47+
48+
# execute a query and iterate over the result
49+
for row in cu.execute("select * from lang"):
50+
print(row)
51+
52+
cx.close()
53+
54+
The sqlite3 module is written by Gerhard Häring <[email protected]>.
55+
"""
56+
2357
from sqlite3.dbapi2 import *
2458

2559

Lib/test/pickletester.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2383,7 +2383,8 @@ def test_bad_getattr(self):
23832383
# Issue #3514: crash when there is an infinite loop in __getattr__
23842384
x = BadGetattr()
23852385
for proto in protocols:
2386-
self.assertRaises(RuntimeError, self.dumps, x, proto)
2386+
with support.infinite_recursion():
2387+
self.assertRaises(RuntimeError, self.dumps, x, proto)
23872388

23882389
def test_reduce_bad_iterator(self):
23892390
# Issue4176: crash when 4th and 5th items of __reduce__()

0 commit comments

Comments
 (0)