summaryrefslogtreecommitdiff
path: root/astroid/inference.py
diff options
context:
space:
mode:
authorMarc Mueller <30130371+cdce8p@users.noreply.github.com>2023-01-30 09:57:17 +0100
committerGitHub <noreply@github.com>2023-01-30 09:57:17 +0100
commit156db06cfb80c1d247aa963fb8661fe69502a45f (patch)
tree56e227025ab5d0cf40e241359b94e941a6ebee95 /astroid/inference.py
parent054519205e3052d91c1a4a6b695fd245c09ddfc4 (diff)
downloadastroid-git-156db06cfb80c1d247aa963fb8661fe69502a45f.tar.gz
Add support for binary union types - Python 3.10 (#1977)
Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
Diffstat (limited to 'astroid/inference.py')
-rw-r--r--astroid/inference.py25
1 files changed, 25 insertions, 0 deletions
diff --git a/astroid/inference.py b/astroid/inference.py
index 59bc4eca..8ec191a4 100644
--- a/astroid/inference.py
+++ b/astroid/inference.py
@@ -15,6 +15,7 @@ from collections.abc import Callable, Generator, Iterable, Iterator
from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union
from astroid import bases, constraint, decorators, helpers, nodes, protocols, util
+from astroid.const import PY310_PLUS
from astroid.context import (
CallContext,
InferenceContext,
@@ -758,6 +759,14 @@ def _bin_op(
)
+def _bin_op_or_union_type(
+ left: bases.UnionType | nodes.ClassDef | nodes.Const,
+ right: bases.UnionType | nodes.ClassDef | nodes.Const,
+) -> Generator[InferenceResult, None, None]:
+ """Create a new UnionType instance for binary or, e.g. int | str."""
+ yield bases.UnionType(left, right)
+
+
def _get_binop_contexts(context, left, right):
"""Get contexts for binary operations.
@@ -817,6 +826,22 @@ def _get_binop_flow(
_bin_op(left, binary_opnode, op, right, context),
_bin_op(right, binary_opnode, op, left, reverse_context, reverse=True),
]
+
+ if (
+ PY310_PLUS
+ and op == "|"
+ and (
+ isinstance(left, (bases.UnionType, nodes.ClassDef))
+ or isinstance(left, nodes.Const)
+ and left.value is None
+ )
+ and (
+ isinstance(right, (bases.UnionType, nodes.ClassDef))
+ or isinstance(right, nodes.Const)
+ and right.value is None
+ )
+ ):
+ methods.extend([functools.partial(_bin_op_or_union_type, left, right)])
return methods