Skip to content

Create UninferableBase #1741

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

Merged
merged 1 commit into from
Feb 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 5 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ Release date: TBA

Refs PyCQA/pylint#7306

* ``Uninferable`` now has the type ``UninferableBase``. This is to facilitate correctly type annotating
code that uses this singleton.

Closes #1680


What's New in astroid 2.14.2?
=============================
Expand Down
8 changes: 4 additions & 4 deletions astroid/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from astroid.bases import Instance
from astroid.context import CallContext, InferenceContext
from astroid.exceptions import InferenceError, NoDefault
from astroid.util import Uninferable
from astroid.util import Uninferable, UninferableBase


class CallSite:
Expand Down Expand Up @@ -44,12 +44,12 @@ def __init__(
self._unpacked_kwargs = self._unpack_keywords(keywords, context=context)

self.positional_arguments = [
arg for arg in self._unpacked_args if arg is not Uninferable
arg for arg in self._unpacked_args if not isinstance(arg, UninferableBase)
]
self.keyword_arguments = {
key: value
for key, value in self._unpacked_kwargs.items()
if value is not Uninferable
if not isinstance(value, UninferableBase)
}

@classmethod
Expand Down Expand Up @@ -142,7 +142,7 @@ def _unpack_args(self, args, context: InferenceContext | None = None):
except StopIteration:
continue

if inferred is Uninferable:
if isinstance(inferred, UninferableBase):
values.append(Uninferable)
continue
if not hasattr(inferred, "elts"):
Expand Down
23 changes: 12 additions & 11 deletions astroid/bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
NameInferenceError,
)
from astroid.typing import InferBinaryOp, InferenceErrorInfo, InferenceResult
from astroid.util import Uninferable, lazy_descriptor, lazy_import
from astroid.util import Uninferable, UninferableBase, lazy_descriptor, lazy_import

if sys.version_info >= (3, 8):
from typing import Literal
Expand Down Expand Up @@ -79,7 +79,9 @@ def _is_property(meth, context: InferenceContext | None = None) -> bool:
if PROPERTIES.intersection(decoratornames):
return True
stripped = {
name.split(".")[-1] for name in decoratornames if name is not Uninferable
name.split(".")[-1]
for name in decoratornames
if not isinstance(name, UninferableBase)
}
if any(name in stripped for name in POSSIBLE_PROPERTIES):
return True
Expand All @@ -89,7 +91,7 @@ def _is_property(meth, context: InferenceContext | None = None) -> bool:
return False
for decorator in meth.decorators.nodes or ():
inferred = helpers.safe_infer(decorator, context=context)
if inferred is None or inferred is Uninferable:
if inferred is None or isinstance(inferred, UninferableBase):
continue
if inferred.__class__.__name__ == "ClassDef":
for base_class in inferred.bases:
Expand Down Expand Up @@ -144,7 +146,7 @@ def infer( # type: ignore[return]


def _infer_stmts(
stmts: Sequence[nodes.NodeNG | type[Uninferable] | Instance],
stmts: Sequence[nodes.NodeNG | UninferableBase | Instance],
context: InferenceContext | None,
frame: nodes.NodeNG | Instance | None = None,
) -> collections.abc.Generator[InferenceResult, None, None]:
Expand All @@ -161,7 +163,7 @@ def _infer_stmts(
context = InferenceContext()

for stmt in stmts:
if stmt is Uninferable:
if isinstance(stmt, UninferableBase):
yield stmt
inferred = True
continue
Expand All @@ -172,8 +174,7 @@ def _infer_stmts(
for constraint_stmt, potential_constraints in constraints.items():
if not constraint_stmt.parent_of(stmt):
stmt_constraints.update(potential_constraints)
# Mypy doesn't recognize that 'stmt' can't be Uninferable
for inf in stmt.infer(context=context): # type: ignore[union-attr]
for inf in stmt.infer(context=context):
if all(constraint.satisfied_by(inf) for constraint in stmt_constraints):
yield inf
inferred = True
Expand Down Expand Up @@ -206,7 +207,7 @@ def _infer_method_result_truth(instance, method_name, context):
try:
context.callcontext = CallContext(args=[], callee=meth)
for value in meth.infer_call_result(instance, context=context):
if value is Uninferable:
if isinstance(value, UninferableBase):
return value
try:
inferred = next(value.infer(context=context))
Expand Down Expand Up @@ -316,7 +317,7 @@ def infer_call_result(

# Otherwise we infer the call to the __call__ dunder normally
for node in self._proxied.igetattr("__call__", context):
if node is Uninferable or not node.callable():
if isinstance(node, UninferableBase) or not node.callable():
continue
for res in node.infer_call_result(caller, context):
inferred = True
Expand Down Expand Up @@ -458,7 +459,7 @@ def _infer_builtin_new(
caller: nodes.Call,
context: InferenceContext,
) -> collections.abc.Generator[
nodes.Const | Instance | type[Uninferable], None, None
nodes.Const | Instance | UninferableBase, None, None
]:
if not caller.args:
return
Expand All @@ -477,7 +478,7 @@ def _infer_builtin_new(

node_context = context.extra_context.get(caller.args[0])
for inferred in caller.args[0].infer(context=node_context):
if inferred is Uninferable:
if isinstance(inferred, UninferableBase):
yield inferred
if isinstance(inferred, nodes.ClassDef):
yield Instance(inferred)
Expand Down
32 changes: 17 additions & 15 deletions astroid/brain/brain_builtin_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,10 +209,10 @@ def _container_generic_inference(node, context, node_type, transform):
inferred = next(arg.infer(context=context))
except (InferenceError, StopIteration) as exc:
raise UseInferenceDefault from exc
if inferred is util.Uninferable:
if isinstance(inferred, util.UninferableBase):
raise UseInferenceDefault
transformed = transform(inferred)
if not transformed or transformed is util.Uninferable:
if not transformed or isinstance(transformed, util.UninferableBase):
raise UseInferenceDefault
return transformed

Expand Down Expand Up @@ -423,7 +423,9 @@ def infer_super(node, context: InferenceContext | None = None):
except (InferenceError, StopIteration) as exc:
raise UseInferenceDefault from exc

if mro_pointer is util.Uninferable or mro_type is util.Uninferable:
if isinstance(mro_pointer, util.UninferableBase) or isinstance(
mro_type, util.UninferableBase
):
# No way we could understand this.
raise UseInferenceDefault

Expand All @@ -445,7 +447,7 @@ def _infer_getattr_args(node, context):
except (InferenceError, StopIteration) as exc:
raise UseInferenceDefault from exc

if obj is util.Uninferable or attr is util.Uninferable:
if isinstance(obj, util.UninferableBase) or isinstance(attr, util.UninferableBase):
# If one of the arguments is something we can't infer,
# then also make the result of the getattr call something
# which is unknown.
Expand All @@ -467,8 +469,8 @@ def infer_getattr(node, context: InferenceContext | None = None):
"""
obj, attr = _infer_getattr_args(node, context)
if (
obj is util.Uninferable
or attr is util.Uninferable
isinstance(obj, util.UninferableBase)
or isinstance(attr, util.UninferableBase)
or not hasattr(obj, "igetattr")
):
return util.Uninferable
Expand Down Expand Up @@ -498,8 +500,8 @@ def infer_hasattr(node, context: InferenceContext | None = None):
try:
obj, attr = _infer_getattr_args(node, context)
if (
obj is util.Uninferable
or attr is util.Uninferable
isinstance(obj, util.UninferableBase)
or isinstance(attr, util.UninferableBase)
or not hasattr(obj, "getattr")
):
return util.Uninferable
Expand Down Expand Up @@ -530,7 +532,7 @@ def infer_callable(node, context: InferenceContext | None = None):
inferred = next(argument.infer(context=context))
except (InferenceError, StopIteration):
return util.Uninferable
if inferred is util.Uninferable:
if isinstance(inferred, util.UninferableBase):
return util.Uninferable
return nodes.Const(inferred.callable())

Expand Down Expand Up @@ -585,11 +587,11 @@ def infer_bool(node, context: InferenceContext | None = None):
inferred = next(argument.infer(context=context))
except (InferenceError, StopIteration):
return util.Uninferable
if inferred is util.Uninferable:
if isinstance(inferred, util.UninferableBase):
return util.Uninferable

bool_value = inferred.bool_value(context=context)
if bool_value is util.Uninferable:
if isinstance(bool_value, util.UninferableBase):
return util.Uninferable
return nodes.Const(bool_value)

Expand All @@ -611,7 +613,7 @@ def infer_slice(node, context: InferenceContext | None = None):
infer_func = partial(helpers.safe_infer, context=context)
args = [infer_func(arg) for arg in args]
for arg in args:
if not arg or arg is util.Uninferable:
if not arg or isinstance(arg, util.UninferableBase):
raise UseInferenceDefault
if not isinstance(arg, nodes.Const):
raise UseInferenceDefault
Expand Down Expand Up @@ -725,7 +727,7 @@ def infer_isinstance(callnode, context: InferenceContext | None = None):
raise UseInferenceDefault("TypeError: " + str(exc)) from exc
except MroError as exc:
raise UseInferenceDefault from exc
if isinstance_bool is util.Uninferable:
if isinstance(isinstance_bool, util.UninferableBase):
raise UseInferenceDefault
return nodes.Const(isinstance_bool)

Expand Down Expand Up @@ -811,7 +813,7 @@ def infer_int(node, context: InferenceContext | None = None):
except (InferenceError, StopIteration) as exc:
raise UseInferenceDefault(str(exc)) from exc

if first_value is util.Uninferable:
if isinstance(first_value, util.UninferableBase):
raise UseInferenceDefault

if isinstance(first_value, nodes.Const) and isinstance(
Expand Down Expand Up @@ -924,7 +926,7 @@ def _is_str_format_call(node: nodes.Call) -> bool:

def _infer_str_format_call(
node: nodes.Call, context: InferenceContext | None = None
) -> Iterator[nodes.Const | type[util.Uninferable]]:
) -> Iterator[nodes.Const | util.UninferableBase]:
"""Return a Const node based on the template and passed arguments."""
call = arguments.CallSite.from_call(node, context=context)
if isinstance(node.func.expr, nodes.Name):
Expand Down
6 changes: 3 additions & 3 deletions astroid/brain/brain_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from astroid.inference_tip import inference_tip
from astroid.manager import AstroidManager
from astroid.typing import InferenceResult
from astroid.util import Uninferable
from astroid.util import Uninferable, UninferableBase

if sys.version_info >= (3, 8):
from typing import Literal
Expand Down Expand Up @@ -446,7 +446,7 @@ def _looks_like_dataclass_decorator(
except (InferenceError, StopIteration):
inferred = Uninferable

if inferred is Uninferable:
if isinstance(inferred, UninferableBase):
if isinstance(node, nodes.Name):
return node.name in decorator_names
if isinstance(node, nodes.Attribute):
Expand Down Expand Up @@ -594,7 +594,7 @@ def _is_init_var(node: nodes.NodeNG) -> bool:

def _infer_instance_from_annotation(
node: nodes.NodeNG, ctx: context.InferenceContext | None = None
) -> Iterator[type[Uninferable] | bases.Instance]:
) -> Iterator[UninferableBase | bases.Instance]:
"""Infer an instance corresponding to the type annotation represented by node.

Currently has limited support for the typing module.
Expand Down
4 changes: 2 additions & 2 deletions astroid/brain/brain_functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from astroid.manager import AstroidManager
from astroid.nodes.node_classes import AssignName, Attribute, Call, Name
from astroid.nodes.scoped_nodes import FunctionDef
from astroid.util import Uninferable
from astroid.util import UninferableBase

LRU_CACHE = "functools.lru_cache"

Expand Down Expand Up @@ -84,7 +84,7 @@ def _functools_partial_inference(
inferred_wrapped_function = next(partial_function.infer(context=context))
except (InferenceError, StopIteration) as exc:
raise UseInferenceDefault from exc
if inferred_wrapped_function is Uninferable:
if isinstance(inferred_wrapped_function, UninferableBase):
raise UseInferenceDefault("Cannot infer the wrapped function")
if not isinstance(inferred_wrapped_function, FunctionDef):
raise UseInferenceDefault("The wrapped function is not a function")
Expand Down
4 changes: 2 additions & 2 deletions astroid/brain/brain_namedtuple_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@


def _infer_first(node, context):
if node is util.Uninferable:
if isinstance(node, util.UninferableBase):
raise UseInferenceDefault
try:
value = next(node.infer(context=context))
except StopIteration as exc:
raise InferenceError from exc
if value is util.Uninferable:
if isinstance(value, util.UninferableBase):
raise UseInferenceDefault()
return value

Expand Down
3 changes: 1 addition & 2 deletions astroid/brain/brain_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
Tuple,
)
from astroid.nodes.scoped_nodes import ClassDef, FunctionDef
from astroid.util import Uninferable

if sys.version_info >= (3, 8):
from typing import Final
Expand Down Expand Up @@ -297,7 +296,7 @@ def infer_typing_alias(
col_offset=assign_name.col_offset,
parent=node.parent,
)
if res != Uninferable and isinstance(res, ClassDef):
if isinstance(res, ClassDef):
# Only add `res` as base if it's a `ClassDef`
# This isn't the case for `typing.Pattern` and `typing.Match`
class_def.postinit(bases=[res], body=[], decorators=None)
Expand Down
7 changes: 2 additions & 5 deletions astroid/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def delayed_assattr(self, node: nodes.AssignAttr) -> None:
try:
frame = node.frame(future=True)
for inferred in node.expr.infer():
if inferred is util.Uninferable:
if isinstance(inferred, util.UninferableBase):
continue
try:
# pylint: disable=unidiomatic-typecheck # We want a narrow check on the
Expand All @@ -255,10 +255,7 @@ def delayed_assattr(self, node: nodes.AssignAttr) -> None:
# Const, Tuple or other containers that inherit from
# `Instance`
continue
elif (
isinstance(inferred, bases.Proxy)
or inferred is util.Uninferable
):
elif isinstance(inferred, (bases.Proxy, util.UninferableBase)):
continue
elif inferred.is_function:
iattrs = inferred.instance_attrs
Expand Down
2 changes: 1 addition & 1 deletion astroid/constraint.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def match(
def satisfied_by(self, inferred: InferenceResult) -> bool:
"""Return True if this constraint is satisfied by the given inferred value."""
# Assume true if uninferable
if inferred is util.Uninferable:
if isinstance(inferred, util.UninferableBase):
return True

# Return the XOR of self.negate and matches(inferred, self.CONST_NONE)
Expand Down
Loading