-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Better callable: Callable[[Arg('x', int), VarArg(str)], int]
now a thing you can do
#2607
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
Changes from 23 commits
249d70f
7ecdcc1
066bd5e
213944b
0e19070
3f2f617
0b69630
f4ccf92
967bb5a
bb5134e
d4a83e1
54a5da9
e79c527
52ffe5c
06416f7
398fbad
2c9ce02
51c6f56
5e679a3
0926fe9
288a8be
6e67ab2
97a859b
1c7d4c6
f153850
be954f5
07ae917
1b97362
552f49e
f2e3663
27e2a9d
793a663
3d212b3
0780149
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,17 +2,28 @@ | |
|
||
from mypy.nodes import ( | ||
Expression, NameExpr, MemberExpr, IndexExpr, TupleExpr, | ||
ListExpr, StrExpr, BytesExpr, UnicodeExpr, EllipsisExpr, | ||
get_member_expr_fullname | ||
ListExpr, StrExpr, BytesExpr, UnicodeExpr, EllipsisExpr, CallExpr, | ||
ARG_POS, ARG_NAMED, get_member_expr_fullname | ||
) | ||
from mypy.fastparse import parse_type_comment | ||
from mypy.types import Type, UnboundType, TypeList, EllipsisType | ||
from mypy.types import ( | ||
Type, UnboundType, TypeList, EllipsisType, AnyType, Optional, CallableArgument, | ||
) | ||
|
||
|
||
class TypeTranslationError(Exception): | ||
"""Exception raised when an expression is not valid as a type.""" | ||
|
||
|
||
def _extract_str(expr: Expression) -> Optional[str]: | ||
if isinstance(expr, NameExpr) and expr.name == 'None': | ||
return None | ||
elif isinstance(expr, StrExpr): | ||
return expr.value | ||
else: | ||
raise TypeTranslationError() | ||
|
||
|
||
def expr_to_unanalyzed_type(expr: Expression) -> Type: | ||
"""Translate an expression to the corresponding type. | ||
|
||
|
@@ -43,6 +54,29 @@ def expr_to_unanalyzed_type(expr: Expression) -> Type: | |
return base | ||
else: | ||
raise TypeTranslationError() | ||
elif isinstance(expr, CallExpr): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Support MemberExpr |
||
if not isinstance(expr.callee, NameExpr): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Also support |
||
raise TypeTranslationError() | ||
arg_const = expr.callee.name | ||
name = None | ||
typ = AnyType(implicit=True) # type: Type | ||
for i, arg in enumerate(expr.args): | ||
if expr.arg_names[i] is not None: | ||
if expr.arg_names[i] == "name": | ||
name = _extract_str(arg) | ||
continue | ||
elif expr.arg_names[i] == "typ": | ||
typ = expr_to_unanalyzed_type(arg) | ||
continue | ||
else: | ||
raise TypeTranslationError() | ||
elif i == 0: | ||
typ = expr_to_unanalyzed_type(arg) | ||
elif i == 1: | ||
name = _extract_str(arg) | ||
else: | ||
raise TypeTranslationError() | ||
return CallableArgument(typ, name, arg_const, expr.line, expr.column) | ||
elif isinstance(expr, ListExpr): | ||
return TypeList([expr_to_unanalyzed_type(t) for t in expr.items], | ||
line=expr.line, column=expr.column) | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,10 +19,12 @@ | |
StarExpr, YieldFromExpr, NonlocalDecl, DictionaryComprehension, | ||
SetComprehension, ComplexExpr, EllipsisExpr, YieldExpr, Argument, | ||
AwaitExpr, TempNode, Expression, Statement, | ||
ARG_POS, ARG_OPT, ARG_STAR, ARG_NAMED, ARG_NAMED_OPT, ARG_STAR2 | ||
ARG_POS, ARG_OPT, ARG_STAR, ARG_NAMED, ARG_NAMED_OPT, ARG_STAR2, | ||
check_arg_names, | ||
) | ||
from mypy.types import ( | ||
Type, CallableType, AnyType, UnboundType, TupleType, TypeList, EllipsisType, | ||
CallableArgument, | ||
) | ||
from mypy import defaults | ||
from mypy import experiments | ||
|
@@ -444,24 +446,12 @@ def make_argument(arg: ast3.arg, default: Optional[ast3.expr], kind: int) -> Arg | |
new_args.append(make_argument(args.kwarg, None, ARG_STAR2)) | ||
names.append(args.kwarg) | ||
|
||
seen_names = set() # type: Set[str] | ||
for name in names: | ||
if name.arg in seen_names: | ||
self.fail("duplicate argument '{}' in function definition".format(name.arg), | ||
name.lineno, name.col_offset) | ||
break | ||
seen_names.add(name.arg) | ||
def fail_arg(msg: str, arg: ast3.arg) -> None: | ||
self.fail(msg, arg.lineno, arg.col_offset) | ||
|
||
return new_args | ||
check_arg_names([name.arg for name in names], names, fail_arg) | ||
|
||
def stringify_name(self, n: ast3.AST) -> str: | ||
if isinstance(n, ast3.Name): | ||
return n.id | ||
elif isinstance(n, ast3.Attribute): | ||
sv = self.stringify_name(n.value) | ||
if sv is not None: | ||
return "{}.{}".format(sv, n.attr) | ||
return None # Can't do it. | ||
return new_args | ||
|
||
# ClassDef(identifier name, | ||
# expr* bases, | ||
|
@@ -474,7 +464,7 @@ def visit_ClassDef(self, n: ast3.ClassDef) -> ClassDef: | |
metaclass_arg = find(lambda x: x.arg == 'metaclass', n.keywords) | ||
metaclass = None | ||
if metaclass_arg: | ||
metaclass = self.stringify_name(metaclass_arg.value) | ||
metaclass = stringify_name(metaclass_arg.value) | ||
if metaclass is None: | ||
metaclass = '<error>' # To be reported later | ||
|
||
|
@@ -965,6 +955,21 @@ class TypeConverter(ast3.NodeTransformer): # type: ignore # typeshed PR #931 | |
def __init__(self, errors: Errors, line: int = -1) -> None: | ||
self.errors = errors | ||
self.line = line | ||
self.node_stack = [] # type: List[ast3.AST] | ||
|
||
def visit(self, node: ast3.AST) -> Type: | ||
"""Modified visit -- keep track of the stack of nodes""" | ||
self.node_stack.append(node) | ||
try: | ||
return super().visit(node) | ||
finally: | ||
self.node_stack.pop() | ||
|
||
def parent(self) -> ast3.AST: | ||
"""Return the AST node above the one we are processing""" | ||
if len(self.node_stack) < 2: | ||
return None | ||
return self.node_stack[-2] | ||
|
||
def fail(self, msg: str, line: int, column: int) -> None: | ||
self.errors.report(line, column, msg) | ||
|
@@ -985,6 +990,49 @@ def visit_NoneType(self, n: Any) -> Type: | |
def translate_expr_list(self, l: Sequence[ast3.AST]) -> List[Type]: | ||
return [self.visit(e) for e in l] | ||
|
||
def visit_Call(self, e: ast3.Call) -> Type: | ||
# Parse the arg constructor | ||
if not isinstance(self.parent(), ast3.List): | ||
return self.generic_visit(e) | ||
f = e.func | ||
constructor = stringify_name(f) | ||
if not constructor: | ||
self.fail("Expected arg constructor name", e.lineno, e.col_offset) | ||
constructor = "BadArgConstructor" | ||
name = None # type: Optional[str] | ||
typ = AnyType(implicit=True) # type: Type | ||
for i, arg in enumerate(e.args): | ||
if i == 0: | ||
typ = self.visit(arg) | ||
elif i == 1: | ||
name = self._extract_str(arg) | ||
else: | ||
self.fail("Too many arguments for argument constructor", | ||
f.lineno, f.col_offset) | ||
for k in e.keywords: | ||
value = k.value | ||
if k.arg == "name": | ||
name = self._extract_str(value) | ||
elif k.arg == "typ": | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Use |
||
typ = self.visit(value) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Make an error if we re-set |
||
else: | ||
self.fail( | ||
'Unexpected argument "{}" for argument constructor'.format(k.arg), | ||
value.lineno, value.col_offset) | ||
return CallableArgument(typ, name, constructor, e.lineno, e.col_offset) | ||
|
||
def translate_argument_list(self, l: Sequence[ast3.AST]) -> TypeList: | ||
return TypeList([self.visit(e) for e in l], line=self.line) | ||
|
||
def _extract_str(self, n: ast3.expr) -> str: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Rename this to be like Figure out handling unicode in python2:
|
||
if isinstance(n, ast3.Str): | ||
return n.s.strip() | ||
elif isinstance(n, ast3.NameConstant) and str(n.value) == 'None': | ||
return None | ||
self.fail('Expected string literal for argument name, got {}'.format( | ||
type(n).__name__), self.line, 0) | ||
return None | ||
|
||
def visit_Name(self, n: ast3.Name) -> Type: | ||
return UnboundType(n.id, line=self.line) | ||
|
||
|
@@ -1036,4 +1084,14 @@ def visit_Ellipsis(self, n: ast3.Ellipsis) -> Type: | |
|
||
# List(expr* elts, expr_context ctx) | ||
def visit_List(self, n: ast3.List) -> Type: | ||
return TypeList(self.translate_expr_list(n.elts), line=self.line) | ||
return self.translate_argument_list(n.elts) | ||
|
||
|
||
def stringify_name(n: ast3.AST) -> Optional[str]: | ||
if isinstance(n, ast3.Name): | ||
return n.id | ||
elif isinstance(n, ast3.Attribute): | ||
sv = stringify_name(n.value) | ||
if sv is not None: | ||
return "{}.{}".format(sv, n.attr) | ||
return None # Can't do it. |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,7 +11,7 @@ | |
from mypy.types import ( | ||
CallableType, EllipsisType, Instance, Overloaded, TupleType, TypedDictType, | ||
TypeList, TypeVarType, UnboundType, UnionType, TypeVisitor, | ||
TypeType | ||
TypeType, CallableArgument, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove from imports |
||
) | ||
from mypy.visitor import NodeVisitor | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,8 +4,8 @@ | |
from mypy.join import is_similar_callables, combine_similar_callables, join_type_list | ||
from mypy.types import ( | ||
Type, AnyType, TypeVisitor, UnboundType, NoneTyp, TypeVarType, | ||
Instance, CallableType, TupleType, TypedDictType, ErasedType, TypeList, UnionType, PartialType, | ||
DeletedType, UninhabitedType, TypeType | ||
Instance, CallableType, TupleType, TypedDictType, ErasedType, TypeList, UnionType, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Undo change to import lines |
||
PartialType, DeletedType, UninhabitedType, TypeType | ||
) | ||
from mypy.subtypes import is_equivalent, is_subtype | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,7 +4,7 @@ | |
from abc import abstractmethod | ||
|
||
from typing import ( | ||
Any, TypeVar, List, Tuple, cast, Set, Dict, Union, Optional | ||
Any, TypeVar, List, Tuple, cast, Set, Dict, Union, Optional, Callable, | ||
) | ||
|
||
import mypy.strconv | ||
|
@@ -2434,3 +2434,44 @@ def get_member_expr_fullname(expr: MemberExpr) -> str: | |
for key, obj in globals().items() | ||
if isinstance(obj, type) and issubclass(obj, SymbolNode) and obj is not SymbolNode | ||
} | ||
|
||
|
||
def check_arg_kinds(arg_kinds: List[int], nodes: List[T], fail: Callable[[str, T], None]) -> None: | ||
is_var_arg = False | ||
is_kw_arg = False | ||
seen_named = False | ||
seen_opt = False | ||
for kind, node in zip(arg_kinds, nodes): | ||
if kind == ARG_POS: | ||
if is_var_arg or is_kw_arg or seen_named or seen_opt: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Change messaging to refer to "var args" |
||
fail("Required positional args may not appear " | ||
"after default, named or star args", | ||
node) | ||
break | ||
elif kind == ARG_OPT: | ||
if is_var_arg or is_kw_arg or seen_named: | ||
fail("Positional default args may not appear after named or star args", node) | ||
break | ||
seen_opt = True | ||
elif kind == ARG_STAR: | ||
if is_var_arg or is_kw_arg or seen_named: | ||
fail("Star args may not appear after named or star args", node) | ||
break | ||
is_var_arg = True | ||
elif kind == ARG_NAMED or kind == ARG_NAMED_OPT: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe we shouldn't allow these after There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
seen_named = True | ||
elif kind == ARG_STAR2: | ||
if is_kw_arg: | ||
fail("You may only have one **kwargs argument", node) | ||
break | ||
is_kw_arg = True | ||
|
||
|
||
def check_arg_names(names: List[str], nodes: List[T], fail: Callable[[str, T], None], | ||
description: str = 'function definition') -> None: | ||
seen_names = set() # type: Set[str] | ||
for name, node in zip(names, nodes): | ||
if name is not None and name in seen_names: | ||
fail("duplicate argument '{}' in {}".format(name, description), node) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Capitalize. |
||
break | ||
seen_names.add(name) |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -468,7 +468,7 @@ def find_type_variables_in_type(self, type: Type) -> List[Tuple[str, TypeVarExpr | |
for arg in type.args: | ||
result.extend(self.find_type_variables_in_type(arg)) | ||
elif isinstance(type, TypeList): | ||
for item in type.items: | ||
for item in type.types: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Land #3113 first, then handle this conflict. Then see if we can remove the |
||
result.extend(self.find_type_variables_in_type(item)) | ||
elif isinstance(type, UnionType): | ||
for item in type.items: | ||
|
@@ -927,7 +927,7 @@ def get_tvars(self, tp: Type) -> List[Tuple[str, TypeVarExpr]]: | |
if isinstance(tp, UnboundType): | ||
tp_args = tp.args | ||
elif isinstance(tp, TypeList): | ||
tp_args = tp.items | ||
tp_args = tp.types | ||
else: | ||
return tvars | ||
for arg in tp_args: | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add comment about why it makes sense to just return
typ
here and elsewhere in this file.