示例#1
0
def make_named_tuple(api: TypeChecker, fields: 'OrderedDict[str, Type]',
                     name: str) -> Type:
    if not fields:
        # No fields specified, so fallback to a subclass of NamedTuple that allows
        # __getattr__ / __setattr__ for any attribute name.
        fallback = api.named_generic_type('django._NamedTupleAnyAttr', [])
    else:
        fallback = build_class_with_annotated_fields(
            api=api,
            base=api.named_generic_type('typing.NamedTuple', []),
            fields=fields,
            name=name)
    return TupleType(list(fields.values()), fallback=fallback)
示例#2
0
 def __init__(self, data_dir: str,
              lib_path: List[str],
              target: int,
              pyversion: Tuple[int, int],
              flags: List[str],
              ignore_prefix: str,
              custom_typing_module: str,
              reports: Reports) -> None:
     self.data_dir = data_dir
     self.errors = Errors()
     self.errors.set_ignore_prefix(ignore_prefix)
     self.lib_path = lib_path
     self.target = target
     self.pyversion = pyversion
     self.flags = flags
     self.custom_typing_module = custom_typing_module
     self.reports = reports
     self.semantic_analyzer = SemanticAnalyzer(lib_path, self.errors,
                                               pyversion=pyversion)
     modules = self.semantic_analyzer.modules
     self.semantic_analyzer_pass3 = ThirdPass(modules, self.errors)
     self.type_checker = TypeChecker(self.errors, modules, self.pyversion)
     self.states = []  # type: List[State]
     self.module_files = {}  # type: Dict[str, str]
     self.module_deps = {}  # type: Dict[Tuple[str, str], bool]
     self.missing_modules = set()  # type: Set[str]
示例#3
0
文件: build.py 项目: silky/mypy
 def __init__(self, data_dir: str,
              lib_path: List[str],
              target: int,
              output_dir: str,
              pyversion: int,
              flags: List[str],
              ignore_prefix: str) -> None:
     self.data_dir = data_dir
     self.errors = Errors()
     self.errors.set_ignore_prefix(ignore_prefix)
     self.lib_path = lib_path
     self.target = target
     self.output_dir = output_dir
     self.pyversion = pyversion
     self.flags = flags
     self.semantic_analyzer = SemanticAnalyzer(lib_path, self.errors)
     self.semantic_analyzer_pass3 = ThirdPass(self.errors)
     self.type_checker = TypeChecker(self.errors,
                                     self.semantic_analyzer.modules,
                                     self.pyversion)
     self.states = List[State]()
     self.module_files = Dict[str, str]()
     self.icode = Dict[str, FuncIcode]()
     self.binary_path = None # type: str
     self.module_deps = Dict[Tuple[str, str], bool]()
示例#4
0
 def __init__(self, data_dir: str,
              lib_path: List[str],
              target: int,
              output_dir: str,
              pyversion: int,
              flags: List[str],
              ignore_prefix: str,
              custom_typing_module: str,
              html_report_dir: str) -> None:
     self.data_dir = data_dir
     self.errors = Errors()
     self.errors.set_ignore_prefix(ignore_prefix)
     self.lib_path = lib_path
     self.target = target
     self.output_dir = output_dir
     self.pyversion = pyversion
     self.flags = flags
     self.custom_typing_module = custom_typing_module
     self.html_report_dir = html_report_dir
     self.semantic_analyzer = SemanticAnalyzer(lib_path, self.errors,
                                               pyversion=pyversion)
     self.semantic_analyzer_pass3 = ThirdPass(self.errors)
     self.type_checker = TypeChecker(self.errors,
                                     self.semantic_analyzer.modules,
                                     self.pyversion)
     self.states = List[State]()
     self.module_files = Dict[str, str]()
     self.module_deps = Dict[Tuple[str, str], bool]()
     self.missing_modules = Set[str]()
示例#5
0
def get_attribute_type(api: TypeChecker, name: str) -> Optional[Instance]:
    if name.find("(") != -1 or name.find("[") != -1:
        return get_generic_type(api, name)

    try:
        klass = NATIVE_TYPES_MAPPING[name]

        return api.named_type("{}.{}".format(klass.__module__,
                                             klass.__qualname__))
    except KeyError:
        pass

    try:
        klass = getattr(kubernetes_client, name, None)

        if klass is None:
            return None

        # ref: mypy.checker.lookup_qualified
        n = api.modules[klass.__module__]
        sym = n.names[klass.__qualname__]

        # ref: mypy.checker.named_type
        node = sym.node
        if isinstance(node, TypeAlias):
            assert isinstance(node.target, Instance)  # type: ignore
            node = node.target.type
        assert isinstance(node, TypeInfo)
        any_type = AnyType(TypeOfAny.from_omitted_generics)
        return Instance(node, [any_type] * len(node.defn.type_vars))
    except KeyError:
        pass

    return None
示例#6
0
def get_generic_type(api: TypeChecker, name: str) -> Optional[Instance]:
    """Parse generic type definition from type hint string

    For example list[str], dict(str, str), etc.
    """

    # TODO: pretty sure this is implemented somewhere inside mypy, byt I was not able to find it
    start: str = ""
    close: Dict[str, str] = {"(": ")", "[": "]"}

    square = name.find("[")
    paren = name.find("(")

    if square != -1 and paren != -1:
        if square < paren:
            start = "["
        elif paren < square:
            start = "("
    elif square != -1:
        start = "["
    elif paren != -1:
        start = "("

    type_name = name.split(start)[0]

    args = name[name.find(start) + 1:name.rfind(close[start])].split(",")

    type_args: List[MypyType] = []

    for arg in args:
        type_arg = get_attribute_type(api, arg.strip())
        if type_arg is not None:
            type_args.append(type_arg)

    return api.named_generic_type(type_name, type_args)
示例#7
0
def make_typeddict(api: TypeChecker, fields: 'OrderedDict[str, Type]',
                   required_keys: typing.Set[str]) -> Type:
    object_type = api.named_generic_type('mypy_extensions._TypedDict', [])
    typed_dict_type = TypedDictType(fields,
                                    required_keys=required_keys,
                                    fallback=object_type)
    return typed_dict_type
示例#8
0
def make_oneoff_named_tuple(api: TypeChecker, name: str,
                            fields: 'OrderedDict[str, MypyType]') -> TupleType:
    current_module = get_current_module(api)
    namedtuple_info = add_new_class_for_module(
        current_module,
        name,
        bases=[api.named_generic_type('typing.NamedTuple', [])],
        fields=fields)
    return TupleType(list(fields.values()),
                     fallback=Instance(namedtuple_info, []))
示例#9
0
def make_oneoff_named_tuple(
        api: TypeChecker,
        name: str,
        fields: "OrderedDict[str, MypyType]",
        extra_bases: Optional[List[Instance]] = None) -> TupleType:
    current_module = get_current_module(api)
    if extra_bases is None:
        extra_bases = []
    namedtuple_info = add_new_class_for_module(
        current_module,
        name,
        bases=[api.named_generic_type("typing.NamedTuple", [])] + extra_bases,
        fields=fields)
    return TupleType(list(fields.values()),
                     fallback=Instance(namedtuple_info, []))
示例#10
0
def make_tuple(api: TypeChecker, fields: typing.List[Type]) -> Type:
    implicit_any = AnyType(TypeOfAny.special_form)
    fallback = api.named_generic_type('builtins.tuple', [implicit_any])
    return TupleType(fields, fallback=fallback)