Skip to content

Commit

Permalink
Add some implicit typing (#1706)
Browse files Browse the repository at this point in the history
* Type most defintions of ``pytype`` and ``qname``

* Add typing to ``implicit_parameters``

* Type ``type()``
  • Loading branch information
DanielNoord authored and Pierre-Sassoulas committed Jul 12, 2022
1 parent 5fa001f commit 162f8ed
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 40 deletions.
16 changes: 11 additions & 5 deletions astroid/bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import collections
import collections.abc
import sys
from collections.abc import Sequence
from typing import Any

Expand All @@ -29,6 +30,11 @@
from astroid.typing import InferenceErrorInfo, InferenceResult
from astroid.util import Uninferable, lazy_descriptor, lazy_import

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

objectmodel = lazy_import("interpreter.objectmodel")
helpers = lazy_import("helpers")
manager = lazy_import("manager")
Expand Down Expand Up @@ -326,7 +332,7 @@ def callable(self):
except AttributeInferenceError:
return False

def pytype(self):
def pytype(self) -> str:
return self._proxied.qname()

def display_type(self):
Expand Down Expand Up @@ -390,7 +396,7 @@ def __repr__(self):
self.__class__.__name__, self._proxied.name, frame.qname(), id(self)
)

def implicit_parameters(self):
def implicit_parameters(self) -> Literal[0]:
return 0

def is_bound(self):
Expand Down Expand Up @@ -470,7 +476,7 @@ def __init__(self, proxy, bound):
super().__init__(proxy)
self.bound = bound

def implicit_parameters(self):
def implicit_parameters(self) -> Literal[0, 1]:
if self.name == "__new__":
# __new__ acts as a classmethod but the class argument is not implicit.
return 0
Expand Down Expand Up @@ -611,7 +617,7 @@ def infer_yield_types(self):
def callable(self):
return False

def pytype(self):
def pytype(self) -> Literal["builtins.generator"]:
return "builtins.generator"

def display_type(self):
Expand All @@ -630,7 +636,7 @@ def __str__(self):
class AsyncGenerator(Generator):
"""Special node representing an async generator"""

def pytype(self):
def pytype(self) -> Literal["builtins.async_generator"]:
return "builtins.async_generator"

def display_type(self):
Expand Down
8 changes: 7 additions & 1 deletion astroid/interpreter/objectmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import itertools
import os
import pprint
import sys
import types
from functools import lru_cache
from typing import TYPE_CHECKING, Any
Expand All @@ -40,6 +41,11 @@
objects = util.lazy_import("objects")
builder = util.lazy_import("builder")

if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

if TYPE_CHECKING:
from astroid import builder
from astroid.objects import Property
Expand Down Expand Up @@ -329,7 +335,7 @@ def attr___get__(self):
class DescriptorBoundMethod(bases.BoundMethod):
"""Bound method which knows how to understand calling descriptor binding."""

def implicit_parameters(self):
def implicit_parameters(self) -> Literal[0]:
# Different than BoundMethod since the signature
# is different.
return 0
Expand Down
23 changes: 8 additions & 15 deletions astroid/nodes/node_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,11 +328,10 @@ def bool_value(self, context=None):
return bool(self.elts)

@abc.abstractmethod
def pytype(self):
def pytype(self) -> str:
"""Get the name of the type that this node represents.
:returns: The name of the type.
:rtype: str
"""

def get_children(self):
Expand Down Expand Up @@ -1987,11 +1986,10 @@ def itered(self):
return [const_factory(elem) for elem in self.value]
raise TypeError(f"Cannot iterate over type {type(self.value)!r}")

def pytype(self):
def pytype(self) -> str:
"""Get the name of the type that this node represents.
:returns: The name of the type.
:rtype: str
"""
return self._proxied.qname()

Expand Down Expand Up @@ -2303,11 +2301,10 @@ def from_elements(cls, items=None):
]
return node

def pytype(self):
def pytype(self) -> Literal["builtins.dict"]:
"""Get the name of the type that this node represents.
:returns: The name of the type.
:rtype: str
"""
return "builtins.dict"

Expand Down Expand Up @@ -3406,11 +3403,10 @@ def __init__(

infer_unary_op: ClassVar[InferUnaryOp[List]]

def pytype(self):
def pytype(self) -> Literal["builtins.list"]:
"""Get the name of the type that this node represents.
:returns: The name of the type.
:rtype: str
"""
return "builtins.list"

Expand Down Expand Up @@ -3644,11 +3640,10 @@ class Set(BaseContainer):

infer_unary_op: ClassVar[InferUnaryOp[Set]]

def pytype(self):
def pytype(self) -> Literal["builtins.set"]:
"""Get the name of the type that this node represents.
:returns: The name of the type.
:rtype: str
"""
return "builtins.set"

Expand Down Expand Up @@ -3736,11 +3731,10 @@ def _proxied(self):
builtins = AstroidManager().builtins_module
return builtins.getattr("slice")[0]

def pytype(self):
def pytype(self) -> Literal["builtins.slice"]:
"""Get the name of the type that this node represents.
:returns: The name of the type.
:rtype: str
"""
return "builtins.slice"

Expand Down Expand Up @@ -4174,11 +4168,10 @@ def __init__(

infer_unary_op: ClassVar[InferUnaryOp[Tuple]]

def pytype(self):
def pytype(self) -> Literal["builtins.tuple"]:
"""Get the name of the type that this node represents.
:returns: The name of the type.
:rtype: str
"""
return "builtins.tuple"

Expand Down Expand Up @@ -4846,7 +4839,7 @@ class Unknown(_base_nodes.AssignTypeNode):

name = "Unknown"

def qname(self):
def qname(self) -> Literal["Unknown"]:
return "Unknown"

def _infer(self, context=None, **kwargs):
Expand Down
21 changes: 7 additions & 14 deletions astroid/nodes/scoped_nodes/scoped_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,11 +377,10 @@ def scope_lookup(self, node, name, offset=0):
return self, ()
return self._scope_lookup(node, name, offset)

def pytype(self):
def pytype(self) -> Literal["builtins.module"]:
"""Get the name of the type that this node represents.
:returns: The name of the type.
:rtype: str
"""
return "builtins.module"

Expand Down Expand Up @@ -1058,16 +1057,14 @@ class Lambda(_base_nodes.FilterStmtsBaseNode, LocalsDictNodeNG):
special_attributes = FunctionModel()
"""The names of special attributes that this function has."""

def implicit_parameters(self):
def implicit_parameters(self) -> Literal[0]:
return 0

# function's type, 'function' | 'method' | 'staticmethod' | 'classmethod'
@property
def type(self):
def type(self) -> Literal["method", "function"]:
"""Whether this is a method or function.
:returns: 'method' if this is a method, 'function' otherwise.
:rtype: str
"""
if self.args.arguments and self.args.arguments[0].name == "self":
if isinstance(self.parent.scope(), ClassDef):
Expand Down Expand Up @@ -1137,11 +1134,10 @@ def postinit(self, args: Arguments, body):
self.args = args
self.body = body

def pytype(self):
def pytype(self) -> Literal["bultins.instancemethod", "builtins.function"]:
"""Get the name of the type that this node represents.
:returns: The name of the type.
:rtype: str
"""
if "method" in self.type:
return "builtins.instancemethod"
Expand Down Expand Up @@ -1473,12 +1469,10 @@ def extra_decorators(self) -> list[node_classes.Call]:
return decorators

@cached_property
def type(self): # pylint: disable=too-many-return-statements
def type(self) -> str: # pylint: disable=too-many-return-statements
"""The function type for this node.
Possible values are: method, function, staticmethod, classmethod.
:type: str
"""
for decorator in self.extra_decorators:
if decorator.func.name in BUILTIN_DESCRIPTORS:
Expand Down Expand Up @@ -2071,7 +2065,7 @@ def doc(self, value: str | None) -> None:
)
self._doc = value

def implicit_parameters(self):
def implicit_parameters(self) -> Literal[1]:
return 1

def implicit_locals(self):
Expand Down Expand Up @@ -2196,11 +2190,10 @@ def block_range(self, lineno):
"""
return self.fromlineno, self.tolineno

def pytype(self):
def pytype(self) -> Literal["builtins.type", "builtins.classobj"]:
"""Get the name of the type that this node represents.
:returns: The name of the type.
:rtype: str
"""
if self.newstyle:
return "builtins.type"
Expand Down
13 changes: 8 additions & 5 deletions astroid/objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@

if sys.version_info >= (3, 8):
from functools import cached_property
from typing import Literal
else:
from typing_extensions import Literal

from astroid.decorators import cachedproperty as cached_property

_T = TypeVar("_T")
Expand All @@ -41,7 +44,7 @@
class FrozenSet(node_classes.BaseContainer):
"""class representing a FrozenSet composite node"""

def pytype(self):
def pytype(self) -> Literal["builtins.frozenset"]:
return "builtins.frozenset"

def _infer(self, context=None, **kwargs: Any):
Expand Down Expand Up @@ -121,7 +124,7 @@ def _proxied(self):
ast_builtins = AstroidManager().builtins_module
return ast_builtins.getattr("super")[0]

def pytype(self):
def pytype(self) -> Literal["builtins.super"]:
return "builtins.super"

def display_type(self):
Expand All @@ -132,7 +135,7 @@ def name(self):
"""Get the name of the MRO pointer."""
return self.mro_pointer.name

def qname(self):
def qname(self) -> Literal["super"]:
return "super"

def igetattr(self, name: str, context: InferenceContext | None = None):
Expand Down Expand Up @@ -307,7 +310,7 @@ def infer_call_result(self, caller=None, context=None):

return super().infer_call_result(caller=caller, context=context)

def qname(self):
def qname(self) -> str:
return self.__class__.__name__


Expand All @@ -332,7 +335,7 @@ def __init__(
special_attributes = util.lazy_descriptor(lambda: objectmodel.PropertyModel())
type = "property"

def pytype(self):
def pytype(self) -> Literal["builtins.property"]:
return "builtins.property"

def infer_call_result(self, caller=None, context=None):
Expand Down

0 comments on commit 162f8ed

Please sign in to comment.