Example #1
0
 def test_bad_annotation(self):
     # type: () -> None
     for bad in [
             '( -> None', '()', ')) -> None', '() -> ', '()->',
             '() -> None x', 'int', 'int -> None', '(Union[]) -> None',
             '(List[int) -> None', '(*int, *str) -> None',
             '(*int, int) -> None', '(**int, *str) -> None',
             '(**int, str) -> None', '(**int, **str) -> None'
     ]:
         with self.assertRaises(ParseError):
             parse_type_comment(bad)
Example #2
0
def infer_annotation(type_comments):
    # type: (List[str]) -> Tuple[List[Argument], AbstractType]
    """Given some type comments, return a single inferred signature.

    Args:
        type_comments: Strings of form '(arg1, ... argN) -> ret'

    Returns: Tuple of (argument types and kinds, return type).
    """
    assert type_comments
    args = {}  # type: Dict[int, Set[Argument]]
    returns = set()
    for comment in type_comments:
        arg_types, return_type = parse_type_comment(comment)
        for i, arg_type in enumerate(arg_types):
            args.setdefault(i, set()).add(arg_type)
        returns.add(return_type)
    combined_args = []
    for i in sorted(args):
        arg_infos = list(args[i])
        kind = argument_kind(arg_infos)
        if kind is None:
            raise InferError('Ambiguous argument kinds:\n' +
                             '\n'.join(type_comments))
        types = [arg.type for arg in arg_infos]
        combined = combine_types(types)
        if kind != ARG_POS and (len(str(combined)) > 120
                                or isinstance(combined, UnionType)):
            # Avoid some noise.
            combined = AnyType()
        combined_args.append(Argument(combined, kind))
    combined_return = combine_types(returns)
    return combined_args, combined_return
Example #3
0
 def assert_type_comment(self, comment, expected):
     # type: (str, Tuple[List[Argument], AbstractType]) -> None
     actual = parse_type_comment(comment)
     assert actual == expected