Skip to content

Commit c48e5e9

Browse files
committed
Merge branch 'add-missing-null-checks' of github.com:chgnrdv/cpython into add-missing-null-checks
2 parents 7ae74e6 + e7cf230 commit c48e5e9

File tree

157 files changed

+13674
-6328
lines changed

Some content is hidden

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

157 files changed

+13674
-6328
lines changed

.github/CODEOWNERS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ configure* @erlend-aasland @corona10
2222
**/*hamt* @1st1
2323
Objects/set* @rhettinger
2424
Objects/dict* @methane @markshannon
25+
Objects/typevarobject.c @JelleZijlstra
2526
Objects/type* @markshannon
2627
Objects/codeobject.c @markshannon
2728
Objects/frameobject.c @markshannon
@@ -33,6 +34,7 @@ Python/flowgraph.c @markshannon @iritkatriel
3334
Python/ast_opt.c @isidentical
3435
Lib/test/test_patma.py @brandtbucher
3536
Lib/test/test_peepholer.py @brandtbucher
37+
Lib/test/test_type_*.py @JelleZijlstra
3638

3739
# Exceptions
3840
Lib/traceback.py @iritkatriel

.github/dependabot.yml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,10 @@ updates:
1212
update-types:
1313
- "version-update:semver-minor"
1414
- "version-update:semver-patch"
15+
- package-ecosystem: "pip"
16+
directory: "/Tools/clinic/"
17+
schedule:
18+
interval: "monthly"
19+
labels:
20+
- "skip issue"
21+
- "skip news"

.github/workflows/mypy.yml

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Workflow to run mypy on select parts of the CPython repo
2+
name: mypy
3+
4+
on:
5+
push:
6+
branches:
7+
- main
8+
pull_request:
9+
paths:
10+
- "Tools/clinic/**"
11+
- ".github/workflows/mypy.yml"
12+
workflow_dispatch:
13+
14+
permissions:
15+
contents: read
16+
17+
env:
18+
PIP_DISABLE_PIP_VERSION_CHECK: 1
19+
FORCE_COLOR: 1
20+
TERM: xterm-256color # needed for FORCE_COLOR to work on mypy on Ubuntu, see https://github.com/python/mypy/issues/13817
21+
22+
concurrency:
23+
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
24+
cancel-in-progress: true
25+
26+
jobs:
27+
mypy:
28+
name: Run mypy on Tools/clinic/
29+
runs-on: ubuntu-latest
30+
timeout-minutes: 10
31+
steps:
32+
- uses: actions/checkout@v3
33+
- uses: actions/setup-python@v4
34+
with:
35+
python-version: "3.x"
36+
cache: pip
37+
cache-dependency-path: Tools/clinic/requirements-dev.txt
38+
- run: pip install -r Tools/clinic/requirements-dev.txt
39+
- run: mypy --config-file Tools/clinic/mypy.ini

Doc/library/ast.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1724,6 +1724,7 @@ Function and class definitions
17241724
body=[
17251725
FunctionDef(
17261726
name='f',
1727+
typeparams=[],
17271728
args=arguments(
17281729
posonlyargs=[],
17291730
args=[
@@ -1847,6 +1848,7 @@ Function and class definitions
18471848
body=[
18481849
ClassDef(
18491850
name='Foo',
1851+
typeparams=[],
18501852
bases=[
18511853
Name(id='base1', ctx=Load()),
18521854
Name(id='base2', ctx=Load())],
@@ -1885,6 +1887,7 @@ Async and await
18851887
body=[
18861888
AsyncFunctionDef(
18871889
name='f',
1890+
typeparams=[],
18881891
args=arguments(
18891892
posonlyargs=[],
18901893
args=[],

Doc/library/atexit.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@ at interpreter termination time they will be run in the order ``C``, ``B``,
2020
program is killed by a signal not handled by Python, when a Python fatal
2121
internal error is detected, or when :func:`os._exit` is called.
2222

23+
**Note:** The effect of registering or unregistering functions from within
24+
a cleanup function is undefined.
25+
2326
.. versionchanged:: 3.7
2427
When used with C-API subinterpreters, registered functions
2528
are local to the interpreter they were registered in.

Doc/library/collections.abc.rst

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,7 @@
1414

1515
.. testsetup:: *
1616

17-
import warnings
18-
# Ignore warning when ByteString is imported
19-
with warnings.catch_warnings(action='ignore', category=DeprecationWarning):
20-
from collections.abc import *
17+
from collections.abc import *
2118
import itertools
2219
__name__ = '<doctest>'
2320

Doc/library/functions.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,13 @@ are always available. They are listed here in alphabetical order.
168168
If :func:`sys.breakpointhook` is not accessible, this function will
169169
raise :exc:`RuntimeError`.
170170

171+
By default, the behavior of :func:`breakpoint` can be changed with
172+
the :envvar:`PYTHONBREAKPOINT` environment variable.
173+
See :func:`sys.breakpointhook` for usage details.
174+
175+
Note that this is not guaranteed if :func:`sys.breakpointhook`
176+
has been replaced.
177+
171178
.. audit-event:: builtins.breakpoint breakpointhook breakpoint
172179

173180
.. versionadded:: 3.7

Doc/library/http.client.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,17 @@ HTTPConnection Objects
394394
one will be automatically generated and transmitted if not provided in
395395
the headers argument.
396396

397+
398+
.. method:: HTTPConnection.get_proxy_response_headers()
399+
400+
Returns a dictionary with the headers of the response received from
401+
the proxy server to the CONNECT request.
402+
403+
If the CONNECT request was not sent, the method returns an empty dictionary.
404+
405+
.. versionadded:: 3.12
406+
407+
397408
.. method:: HTTPConnection.connect()
398409

399410
Connect to the server specified when the object was created. By default,

Doc/library/logging.config.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ in :mod:`logging` itself) and defining handlers which are declared either in
111111
they or their ancestors are explicitly named
112112
in the logging configuration.
113113

114-
:param encoding: The encoding used to open file when *fname* is filename.
114+
:param encoding: The encoding used to open file when *fname* is filename.
115115

116116
.. versionchanged:: 3.4
117117
An instance of a subclass of :class:`~configparser.RawConfigParser` is

Doc/library/random.rst

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -334,8 +334,10 @@ be found in any statistics text.
334334

335335
.. function:: gammavariate(alpha, beta)
336336

337-
Gamma distribution. (*Not* the gamma function!) Conditions on the
338-
parameters are ``alpha > 0`` and ``beta > 0``.
337+
Gamma distribution. (*Not* the gamma function!) The shape and
338+
scale parameters, *alpha* and *beta*, must have positive values.
339+
(Calling conventions vary and some sources define 'beta'
340+
as the inverse of the scale).
339341

340342
The probability distribution function is::
341343

@@ -346,7 +348,8 @@ be found in any statistics text.
346348

347349
.. function:: gauss(mu=0.0, sigma=1.0)
348350

349-
Normal distribution, also called the Gaussian distribution. *mu* is the mean,
351+
Normal distribution, also called the Gaussian distribution.
352+
*mu* is the mean,
350353
and *sigma* is the standard deviation. This is slightly faster than
351354
the :func:`normalvariate` function defined below.
352355

Doc/library/typing.rst

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020
This module provides runtime support for type hints. The most fundamental
2121
support consists of the types :data:`Any`, :data:`Union`, :data:`Callable`,
22-
:class:`TypeVar`, and :class:`Generic`. For a full specification, please see
22+
:class:`TypeVar`, and :class:`Generic`. For a specification, please see
2323
:pep:`484`. For a simplified introduction to type hints, see :pep:`483`.
2424

2525

@@ -592,7 +592,7 @@ The module defines the following classes, functions and decorators.
592592
when the checked program targets Python 3.9 or newer.
593593

594594
The deprecated types will be removed from the :mod:`typing` module
595-
in the first Python version released 5 years after the release of Python 3.9.0.
595+
no sooner than the first Python version released 5 years after the release of Python 3.9.0.
596596
See details in :pep:`585`—*Type Hinting Generics In Standard Collections*.
597597

598598

@@ -1291,6 +1291,8 @@ These are not used in annotations. They are building blocks for creating generic
12911291
U = TypeVar('U', bound=str|bytes) # Can be any subtype of the union str|bytes
12921292
V = TypeVar('V', bound=SupportsAbs) # Can be anything with an __abs__ method
12931293

1294+
.. _typing-constrained-typevar:
1295+
12941296
Using a *constrained* type variable, however, means that the ``TypeVar``
12951297
can only ever be solved as being exactly one of the constraints given::
12961298

@@ -1550,7 +1552,7 @@ These are not used in annotations. They are building blocks for creating generic
15501552

15511553
.. data:: AnyStr
15521554

1553-
``AnyStr`` is a :class:`constrained type variable <TypeVar>` defined as
1555+
``AnyStr`` is a :ref:`constrained type variable <typing-constrained-typevar>` defined as
15541556
``AnyStr = TypeVar('AnyStr', str, bytes)``.
15551557

15561558
It is meant to be used for functions that may accept any kind of string
@@ -2112,7 +2114,7 @@ Other concrete types
21122114
Python 2 is no longer supported, and most type checkers also no longer
21132115
support type checking Python 2 code. Removal of the alias is not
21142116
currently planned, but users are encouraged to use
2115-
:class:`str` instead of ``Text`` wherever possible.
2117+
:class:`str` instead of ``Text``.
21162118

21172119
Abstract Base Classes
21182120
---------------------

Doc/library/urllib.parse.rst

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,10 @@ or on combining URL components into a URL string.
159159
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
160160
params='', query='', fragment='')
161161

162+
.. warning::
163+
164+
:func:`urlparse` does not perform validation. See :ref:`URL parsing
165+
security <url-parsing-security>` for details.
162166

163167
.. versionchanged:: 3.2
164168
Added IPv6 URL parsing capabilities.
@@ -324,8 +328,14 @@ or on combining URL components into a URL string.
324328
``#``, ``@``, or ``:`` will raise a :exc:`ValueError`. If the URL is
325329
decomposed before parsing, no error will be raised.
326330

327-
Following the `WHATWG spec`_ that updates RFC 3986, ASCII newline
328-
``\n``, ``\r`` and tab ``\t`` characters are stripped from the URL.
331+
Following some of the `WHATWG spec`_ that updates RFC 3986, leading C0
332+
control and space characters are stripped from the URL. ``\n``,
333+
``\r`` and tab ``\t`` characters are removed from the URL at any position.
334+
335+
.. warning::
336+
337+
:func:`urlsplit` does not perform validation. See :ref:`URL parsing
338+
security <url-parsing-security>` for details.
329339

330340
.. versionchanged:: 3.6
331341
Out-of-range port numbers now raise :exc:`ValueError`, instead of
@@ -338,6 +348,9 @@ or on combining URL components into a URL string.
338348
.. versionchanged:: 3.10
339349
ASCII newline and tab characters are stripped from the URL.
340350

351+
.. versionchanged:: 3.12
352+
Leading WHATWG C0 control and space characters are stripped from the URL.
353+
341354
.. _WHATWG spec: https://url.spec.whatwg.org/#concept-basic-url-parser
342355

343356
.. function:: urlunsplit(parts)
@@ -414,6 +427,35 @@ or on combining URL components into a URL string.
414427
or ``scheme://host/path``). If *url* is not a wrapped URL, it is returned
415428
without changes.
416429

430+
.. _url-parsing-security:
431+
432+
URL parsing security
433+
--------------------
434+
435+
The :func:`urlsplit` and :func:`urlparse` APIs do not perform **validation** of
436+
inputs. They may not raise errors on inputs that other applications consider
437+
invalid. They may also succeed on some inputs that might not be considered
438+
URLs elsewhere. Their purpose is for practical functionality rather than
439+
purity.
440+
441+
Instead of raising an exception on unusual input, they may instead return some
442+
component parts as empty strings. Or components may contain more than perhaps
443+
they should.
444+
445+
We recommend that users of these APIs where the values may be used anywhere
446+
with security implications code defensively. Do some verification within your
447+
code before trusting a returned component part. Does that ``scheme`` make
448+
sense? Is that a sensible ``path``? Is there anything strange about that
449+
``hostname``? etc.
450+
451+
What constitutes a URL is not universally well defined. Different applications
452+
have different needs and desired constraints. For instance the living `WHATWG
453+
spec`_ describes what user facing web clients such as a web browser require.
454+
While :rfc:`3986` is more general. These functions incorporate some aspects of
455+
both, but cannot be claimed compliant with either. The APIs and existing user
456+
code with expectations on specific behaviors predate both standards leading us
457+
to be very cautious about making API behavior changes.
458+
417459
.. _parsing-ascii-encoded-bytes:
418460

419461
Parsing ASCII Encoded Bytes

Doc/whatsnew/3.12.rst

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -831,8 +831,8 @@ Pending Removal in Python 3.14
831831
For use in typing, prefer a union, like ``bytes | bytearray``, or :class:`collections.abc.Buffer`.
832832
(Contributed by Shantanu Jain in :gh:`91896`.)
833833

834-
* :class:`typing.ByteString`, deprecated since Python 3.9, now causes an
835-
:exc:`DeprecationWarning` to be emitted when it is used or accessed.
834+
* :class:`typing.ByteString`, deprecated since Python 3.9, now causes a
835+
:exc:`DeprecationWarning` to be emitted when it is used.
836836

837837
* Creating immutable types (:data:`Py_TPFLAGS_IMMUTABLETYPE`) with mutable
838838
bases using the C API.
@@ -1204,6 +1204,8 @@ Build Changes
12041204

12051205
(Contributed by Zhang Na in :gh:`90656`.)
12061206

1207+
* ``PYTHON_FOR_REGEN`` now require Python 3.10 or newer.
1208+
12071209

12081210
C API Changes
12091211
=============

Grammar/python.gram

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,7 @@ simple_stmts[asdl_stmt_seq*]:
112112
# will throw a SyntaxError.
113113
simple_stmt[stmt_ty] (memo):
114114
| assignment
115+
| &"type" type_alias
115116
| e=star_expressions { _PyAST_Expr(e, EXTRA) }
116117
| &'return' return_stmt
117118
| &('import' | 'from') import_stmt
@@ -252,8 +253,8 @@ class_def[stmt_ty]:
252253

253254
class_def_raw[stmt_ty]:
254255
| invalid_class_def_raw
255-
| 'class' a=NAME b=['(' z=[arguments] ')' { z }] ':' c=block {
256-
_PyAST_ClassDef(a->v.Name.id,
256+
| 'class' a=NAME t=[type_params] b=['(' z=[arguments] ')' { z }] ':' c=block {
257+
_PyAST_ClassDef(a->v.Name.id, t,
257258
(b) ? ((expr_ty) b)->v.Call.args : NULL,
258259
(b) ? ((expr_ty) b)->v.Call.keywords : NULL,
259260
c, NULL, EXTRA) }
@@ -267,16 +268,16 @@ function_def[stmt_ty]:
267268

268269
function_def_raw[stmt_ty]:
269270
| invalid_def_raw
270-
| 'def' n=NAME &&'(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block {
271-
_PyAST_FunctionDef(n->v.Name.id,
271+
| 'def' n=NAME t=[type_params] &&'(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block {
272+
_PyAST_FunctionDef(n->v.Name.id, t,
272273
(params) ? params : CHECK(arguments_ty, _PyPegen_empty_arguments(p)),
273274
b, NULL, a, NEW_TYPE_COMMENT(p, tc), EXTRA) }
274-
| ASYNC 'def' n=NAME &&'(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block {
275+
| ASYNC 'def' n=NAME t=[type_params] &&'(' params=[params] ')' a=['->' z=expression { z }] &&':' tc=[func_type_comment] b=block {
275276
CHECK_VERSION(
276277
stmt_ty,
277278
5,
278279
"Async functions are",
279-
_PyAST_AsyncFunctionDef(n->v.Name.id,
280+
_PyAST_AsyncFunctionDef(n->v.Name.id, t,
280281
(params) ? params : CHECK(arguments_ty, _PyPegen_empty_arguments(p)),
281282
b, NULL, a, NEW_TYPE_COMMENT(p, tc), EXTRA)
282283
) }
@@ -628,6 +629,39 @@ keyword_patterns[asdl_seq*]:
628629
keyword_pattern[KeyPatternPair*]:
629630
| arg=NAME '=' value=pattern { _PyPegen_key_pattern_pair(p, arg, value) }
630631

632+
# Type statement
633+
# ---------------
634+
635+
type_alias[stmt_ty]:
636+
| "type" n=NAME t=[type_params] '=' b=expression {
637+
CHECK_VERSION(stmt_ty, 12, "Type statement is",
638+
_PyAST_TypeAlias(CHECK(expr_ty, _PyPegen_set_expr_context(p, n, Store)), t, b, EXTRA)) }
639+
640+
# Type parameter declaration
641+
# --------------------------
642+
643+
type_params[asdl_typeparam_seq*]: '[' t=type_param_seq ']' {
644+
CHECK_VERSION(asdl_typeparam_seq *, 12, "Type parameter lists are", t) }
645+
646+
type_param_seq[asdl_typeparam_seq*]: a[asdl_typeparam_seq*]=','.type_param+ [','] { a }
647+
648+
type_param[typeparam_ty] (memo):
649+
| a=NAME b=[type_param_bound] { _PyAST_TypeVar(a->v.Name.id, b, EXTRA) }
650+
| '*' a=NAME colon=":" e=expression {
651+
RAISE_SYNTAX_ERROR_STARTING_FROM(colon, e->kind == Tuple_kind
652+
? "cannot use constraints with TypeVarTuple"
653+
: "cannot use bound with TypeVarTuple")
654+
}
655+
| '*' a=NAME { _PyAST_TypeVarTuple(a->v.Name.id, EXTRA) }
656+
| '**' a=NAME colon=":" e=expression {
657+
RAISE_SYNTAX_ERROR_STARTING_FROM(colon, e->kind == Tuple_kind
658+
? "cannot use constraints with ParamSpec"
659+
: "cannot use bound with ParamSpec")
660+
}
661+
| '**' a=NAME { _PyAST_ParamSpec(a->v.Name.id, EXTRA) }
662+
663+
type_param_bound[expr_ty]: ":" e=expression { e }
664+
631665
# EXPRESSIONS
632666
# -----------
633667

0 commit comments

Comments
 (0)