Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Python 3.12 #2219

Merged
merged 19 commits into from
Jun 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: [3.8, 3.9, "3.10", "3.11"]
python-version: [3.8, 3.9, "3.10", "3.11", "3.12-dev"]
outputs:
python-key: ${{ steps.generate-python-key.outputs.key }}
steps:
Expand Down Expand Up @@ -138,7 +138,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: [3.8, 3.9, "3.10", "3.11"]
python-version: [3.8, 3.9, "3.10", "3.11", "3.12-dev"]
steps:
- name: Set temp directory
run: echo "TEMP=$env:USERPROFILE\AppData\Local\Temp" >> $env:GITHUB_ENV
Expand Down
4 changes: 4 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ What's New in astroid 3.0.0?
=============================
Release date: TBA

* Add support for Python 3.12, including PEP 695 type parameter syntax.

Closes #2201

* Remove support for Python 3.7.

Refs #2137
Expand Down
31 changes: 31 additions & 0 deletions astroid/brain/brain_datetime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt

import textwrap

from astroid.brain.helpers import register_module_extender
from astroid.builder import AstroidBuilder
from astroid.const import PY312_PLUS
from astroid.manager import AstroidManager


def datetime_transform():
"""The datetime module was C-accelerated in Python 3.12, so we
lack a Python source."""
return AstroidBuilder(AstroidManager()).string_build(
textwrap.dedent(
"""
class date: ...
class time: ...
class datetime(date): ...
class timedelta: ...
class tzinfo: ...
class timezone(tzinfo): ...
"""
)
)


if PY312_PLUS:
register_module_extender(AstroidManager(), "datetime", datetime_transform)
37 changes: 34 additions & 3 deletions astroid/brain/brain_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@

from __future__ import annotations

import textwrap
import typing
from collections.abc import Iterator
from functools import partial
from typing import Final

from astroid import context, extract_node, inference_tip
from astroid.builder import _extract_single_node
from astroid.const import PY39_PLUS
from astroid.brain.helpers import register_module_extender
from astroid.builder import AstroidBuilder, _extract_single_node
from astroid.const import PY39_PLUS, PY312_PLUS
from astroid.exceptions import (
AttributeInferenceError,
InferenceError,
Expand Down Expand Up @@ -231,7 +233,8 @@ def _looks_like_typing_alias(node: Call) -> bool:
"""
return (
isinstance(node.func, Name)
and node.func.name == "_alias"
# TODO: remove _DeprecatedGenericAlias when Py3.14 min
and node.func.name in {"_alias", "_DeprecatedGenericAlias"}
and (
# _alias function works also for builtins object such as list and dict
isinstance(node.args[0], (Attribute, Name))
Expand Down Expand Up @@ -273,6 +276,8 @@ def infer_typing_alias(

:param node: call node
:param context: inference context

# TODO: evaluate if still necessary when Py3.12 is minimum
"""
if (
not isinstance(node.parent, Assign)
Expand Down Expand Up @@ -415,6 +420,29 @@ def infer_typing_cast(
return node.args[1].infer(context=ctx)


def _typing_transform():
return AstroidBuilder(AstroidManager()).string_build(
textwrap.dedent(
"""
class Generic:
@classmethod
def __class_getitem__(cls, item): return cls
class ParamSpec: ...
class ParamSpecArgs: ...
class ParamSpecKwargs: ...
class TypeAlias: ...
class Type:
@classmethod
def __class_getitem__(cls, item): return cls
class TypeVar:
@classmethod
def __class_getitem__(cls, item): return cls
class TypeVarTuple: ...
"""
)
)


AstroidManager().register_transform(
Call,
inference_tip(infer_typing_typevar_or_newtype),
Expand Down Expand Up @@ -442,3 +470,6 @@ def infer_typing_cast(
AstroidManager().register_transform(
Call, inference_tip(infer_special_alias), _looks_like_special_alias
)

if PY312_PLUS:
register_module_extender(AstroidManager(), "typing", _typing_transform)
1 change: 1 addition & 0 deletions astroid/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
PY39_PLUS = sys.version_info >= (3, 9)
PY310_PLUS = sys.version_info >= (3, 10)
PY311_PLUS = sys.version_info >= (3, 11)
PY312_PLUS = sys.version_info >= (3, 12)

WIN32 = sys.platform == "win32"

Expand Down
4 changes: 4 additions & 0 deletions astroid/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ def infer_end(
nodes.Lambda._infer = infer_end # type: ignore[assignment]
nodes.Const._infer = infer_end # type: ignore[assignment]
nodes.Slice._infer = infer_end # type: ignore[assignment]
nodes.TypeAlias._infer = infer_end # type: ignore[assignment]
nodes.TypeVar._infer = infer_end # type: ignore[assignment]
nodes.ParamSpec._infer = infer_end # type: ignore[assignment]
nodes.TypeVarTuple._infer = infer_end # type: ignore[assignment]


def _infer_sequence_helper(
Expand Down
12 changes: 12 additions & 0 deletions astroid/nodes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
NamedExpr,
NodeNG,
Nonlocal,
ParamSpec,
Pass,
Pattern,
Raise,
Expand All @@ -83,6 +84,9 @@
TryFinally,
TryStar,
Tuple,
TypeAlias,
TypeVar,
TypeVarTuple,
UnaryOp,
Unknown,
While,
Expand Down Expand Up @@ -180,6 +184,8 @@
NamedExpr,
NodeNG,
Nonlocal,
ParamSpec,
TypeVarTuple,
Pass,
Pattern,
Raise,
Expand All @@ -193,6 +199,8 @@
TryFinally,
TryStar,
Tuple,
TypeAlias,
TypeVar,
UnaryOp,
Unknown,
While,
Expand Down Expand Up @@ -271,6 +279,7 @@
"NamedExpr",
"NodeNG",
"Nonlocal",
"ParamSpec",
"Pass",
"Position",
"Raise",
Expand All @@ -285,6 +294,9 @@
"TryFinally",
"TryStar",
"Tuple",
"TypeAlias",
"TypeVar",
"TypeVarTuple",
"UnaryOp",
"Unknown",
"unpack_infer",
Expand Down
18 changes: 18 additions & 0 deletions astroid/nodes/as_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ def visit_classdef(self, node) -> str:
args += [n.accept(self) for n in node.keywords]
args_str = f"({', '.join(args)})" if args else ""
docs = self._docs_dedent(node.doc_node)
# TODO: handle type_params
return "\n\n{}class {}{}:{}\n{}\n".format(
decorate, node.name, args_str, docs, self._stmt_list(node.body)
)
Expand Down Expand Up @@ -330,6 +331,7 @@ def handle_functiondef(self, node, keyword) -> str:
if node.returns:
return_annotation = " -> " + node.returns.as_string()
trailer = return_annotation + ":"
# TODO: handle type_params
def_format = "\n%s%s %s(%s)%s%s\n%s"
return def_format % (
decorate,
Expand Down Expand Up @@ -431,6 +433,10 @@ def visit_nonlocal(self, node) -> str:
"""return an astroid.Nonlocal node as string"""
return f"nonlocal {', '.join(node.names)}"

def visit_paramspec(self, node: nodes.ParamSpec) -> str:
"""return an astroid.ParamSpec node as string"""
return node.name.accept(self)

def visit_pass(self, node) -> str:
"""return an astroid.Pass node as string"""
return "pass"
Expand Down Expand Up @@ -517,6 +523,18 @@ def visit_tuple(self, node) -> str:
return f"({node.elts[0].accept(self)}, )"
return f"({', '.join(child.accept(self) for child in node.elts)})"

def visit_typealias(self, node: nodes.TypeAlias) -> str:
"""return an astroid.TypeAlias node as string"""
return node.name.accept(self) if node.name else "_"

def visit_typevar(self, node: nodes.TypeVar) -> str:
"""return an astroid.TypeVar node as string"""
return node.name.accept(self) if node.name else "_"

def visit_typevartuple(self, node: nodes.TypeVarTuple) -> str:
"""return an astroid.TypeVarTuple node as string"""
return "*" + node.name.accept(self) if node.name else ""

def visit_unaryop(self, node) -> str:
"""return an astroid.UnaryOp node as string"""
if node.op == "not":
Expand Down
Loading