summaryrefslogtreecommitdiff
path: root/astroid
diff options
context:
space:
mode:
authorMarc Mueller <30130371+cdce8p@users.noreply.github.com>2021-09-02 14:42:22 +0200
committerGitHub <noreply@github.com>2021-09-02 14:42:22 +0200
commit40ea1a3b8e52bbfed43deb1725cde461f4bd8a96 (patch)
tree2007f0e3becff62146f6c2ab793e8054b36366be /astroid
parentbc14d8efc0d09b2709e2817890757c6dabff0b84 (diff)
downloadastroid-git-40ea1a3b8e52bbfed43deb1725cde461f4bd8a96.tar.gz
Deprecate some default values for node init calls (#1157)
* Fix missing name value * Add deprecation warnings to Name nodes * Add deprecation warnings to Attribute nodes * Add deprecation warnings for op attribute * Add deprecation warning to Import nodes * Add missing 'can be None' comment * Add changelog entry * Use decorator to emit DeprecationWarnings * Require typing-extensions>=3.10
Diffstat (limited to 'astroid')
-rw-r--r--astroid/decorators.py69
-rw-r--r--astroid/nodes/node_classes.py13
-rw-r--r--astroid/raw_building.py3
3 files changed, 82 insertions, 3 deletions
diff --git a/astroid/decorators.py b/astroid/decorators.py
index b3f3d026..9630868b 100644
--- a/astroid/decorators.py
+++ b/astroid/decorators.py
@@ -18,6 +18,10 @@
""" A few useful function/method decorators."""
import functools
+import inspect
+import sys
+import warnings
+from typing import Callable, TypeVar
import wrapt
@@ -25,6 +29,14 @@ from astroid import util
from astroid.context import InferenceContext
from astroid.exceptions import InferenceError
+if sys.version_info >= (3, 10):
+ from typing import ParamSpec
+else:
+ from typing_extensions import ParamSpec
+
+R = TypeVar("R")
+P = ParamSpec("P")
+
@wrapt.decorator
def cached(func, instance, args, kwargs):
@@ -137,3 +149,60 @@ def raise_if_nothing_inferred(func, instance, args, kwargs):
) from error
yield from generator
+
+
+def deprecate_default_argument_values(
+ astroid_version: str = "3.0", **arguments: str
+) -> Callable[[Callable[P, R]], Callable[P, R]]:
+ """Decorator which emitts a DeprecationWarning if any arguments specified
+ are None or not passed at all.
+
+ Arguments should be a key-value mapping, with the key being the argument to check
+ and the value being a type annotation as string for the value of the argument.
+ """
+ # Helpful links
+ # Decorator for DeprecationWarning: https://stackoverflow.com/a/49802489
+ # Typing of stacked decorators: https://stackoverflow.com/a/68290080
+
+ def deco(func: Callable[P, R]) -> Callable[P, R]:
+ """Decorator function."""
+
+ @functools.wraps(func)
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ """Emit DeprecationWarnings if conditions are met."""
+
+ keys = list(inspect.signature(func).parameters.keys())
+ for arg, type_annotation in arguments.items():
+ try:
+ index = keys.index(arg)
+ except ValueError:
+ raise Exception(
+ f"Can't find argument '{arg}' for '{args[0].__class__.__qualname__}'"
+ ) from None
+ if (
+ # Check kwargs
+ # - if found, check it's not None
+ (arg in kwargs and kwargs[arg] is None)
+ # Check args
+ # - make sure not in kwargs
+ # - len(args) needs to be long enough, if too short
+ # arg can't be in args either
+ # - args[index] should not be None
+ or arg not in kwargs
+ and (
+ index == -1
+ or len(args) <= index
+ or (len(args) > index and args[index] is None)
+ )
+ ):
+ warnings.warn(
+ f"'{arg}' will be a required attribute for "
+ f"'{args[0].__class__.__qualname__}.{func.__name__}' in astroid {astroid_version} "
+ f"('{arg}' should be of type: '{type_annotation}')",
+ DeprecationWarning,
+ )
+ return func(*args, **kwargs)
+
+ return wrapper
+
+ return deco
diff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py
index 6f5609da..254e479e 100644
--- a/astroid/nodes/node_classes.py
+++ b/astroid/nodes/node_classes.py
@@ -590,6 +590,7 @@ class AssignName(
_other_fields = ("name",)
+ @decorators.deprecate_default_argument_values(name="str")
def __init__(
self,
name: Optional[str] = None,
@@ -630,6 +631,7 @@ class DelName(
_other_fields = ("name",)
+ @decorators.deprecate_default_argument_values(name="str")
def __init__(
self,
name: Optional[str] = None,
@@ -671,6 +673,7 @@ class Name(mixins.NoChildrenMixin, LookupMixIn, NodeNG):
_other_fields = ("name",)
+ @decorators.deprecate_default_argument_values(name="str")
def __init__(
self,
name: Optional[str] = None,
@@ -1099,6 +1102,7 @@ class AssignAttr(mixins.ParentAssignTypeMixin, NodeNG):
_astroid_fields = ("expr",)
_other_fields = ("attrname",)
+ @decorators.deprecate_default_argument_values(attrname="str")
def __init__(
self,
attrname: Optional[str] = None,
@@ -1224,7 +1228,7 @@ class Assign(mixins.AssignTypeMixin, Statement):
self.value: Optional[NodeNG] = None
"""The value being assigned to the variables."""
- self.type_annotation: Optional[NodeNG] = None
+ self.type_annotation: Optional[NodeNG] = None # can be None
"""If present, this will contain the type annotation passed by a type comment"""
super().__init__(lineno=lineno, col_offset=col_offset, parent=parent)
@@ -1346,6 +1350,7 @@ class AugAssign(mixins.AssignTypeMixin, Statement):
_astroid_fields = ("target", "value")
_other_fields = ("op",)
+ @decorators.deprecate_default_argument_values(op="str")
def __init__(
self,
op: Optional[str] = None,
@@ -1437,6 +1442,7 @@ class BinOp(NodeNG):
_astroid_fields = ("left", "right")
_other_fields = ("op",)
+ @decorators.deprecate_default_argument_values(op="str")
def __init__(
self,
op: Optional[str] = None,
@@ -1526,6 +1532,7 @@ class BoolOp(NodeNG):
_astroid_fields = ("values",)
_other_fields = ("op",)
+ @decorators.deprecate_default_argument_values(op="str")
def __init__(
self,
op: Optional[str] = None,
@@ -2040,6 +2047,7 @@ class DelAttr(mixins.ParentAssignTypeMixin, NodeNG):
_astroid_fields = ("expr",)
_other_fields = ("attrname",)
+ @decorators.deprecate_default_argument_values(attrname="str")
def __init__(
self,
attrname: Optional[str] = None,
@@ -2671,6 +2679,7 @@ class Attribute(NodeNG):
_astroid_fields = ("expr",)
_other_fields = ("attrname",)
+ @decorators.deprecate_default_argument_values(attrname="str")
def __init__(
self,
attrname: Optional[str] = None,
@@ -2957,6 +2966,7 @@ class Import(mixins.NoChildrenMixin, mixins.ImportFromMixin, Statement):
_other_fields = ("names",)
+ @decorators.deprecate_default_argument_values(names="list[tuple[str, str | None]]")
def __init__(
self,
names: Optional[typing.List[typing.Tuple[str, Optional[str]]]] = None,
@@ -3733,6 +3743,7 @@ class UnaryOp(NodeNG):
_astroid_fields = ("operand",)
_other_fields = ("op",)
+ @decorators.deprecate_default_argument_values(op="str")
def __init__(
self,
op: Optional[str] = None,
diff --git a/astroid/raw_building.py b/astroid/raw_building.py
index 31ff22f7..225137e7 100644
--- a/astroid/raw_building.py
+++ b/astroid/raw_building.py
@@ -118,8 +118,7 @@ def build_class(name, basenames=(), doc=None):
"""create and initialize an astroid ClassDef node"""
node = nodes.ClassDef(name, doc)
for base in basenames:
- basenode = nodes.Name()
- basenode.name = base
+ basenode = nodes.Name(name=base)
node.bases.append(basenode)
basenode.parent = node
return node