本文整理汇总了Python中mypy.nodes.TypeInfo类的典型用法代码示例。如果您正苦于以下问题:Python TypeInfo类的具体用法?Python TypeInfo怎么用?Python TypeInfo使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TypeInfo类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process_type_info
def process_type_info(self, info: TypeInfo) -> None:
target = self.scope.current_full_target()
for base in info.bases:
self.add_type_dependencies(base, target=target)
if info.tuple_type:
self.add_type_dependencies(info.tuple_type, target=make_trigger(target))
if info.typeddict_type:
self.add_type_dependencies(info.typeddict_type, target=make_trigger(target))
if info.declared_metaclass:
self.add_type_dependencies(info.declared_metaclass, target=make_trigger(target))
self.add_type_alias_deps(self.scope.current_target())
for name, node in info.names.items():
if isinstance(node.node, Var):
for base_info in non_trivial_bases(info):
# If the type of an attribute changes in a base class, we make references
# to the attribute in the subclass stale.
self.add_dependency(make_trigger(base_info.fullname() + '.' + name),
target=make_trigger(info.fullname() + '.' + name))
for base_info in non_trivial_bases(info):
for name, node in base_info.names.items():
self.add_dependency(make_trigger(base_info.fullname() + '.' + name),
target=make_trigger(info.fullname() + '.' + name))
self.add_dependency(make_trigger(base_info.fullname() + '.__init__'),
target=make_trigger(info.fullname() + '.__init__'))
self.add_dependency(make_trigger(base_info.fullname() + '.__new__'),
target=make_trigger(info.fullname() + '.__new__'))
示例2: dump_typeinfo
def dump_typeinfo(self, info: TypeInfo) -> List[str]:
if info.fullname() == 'enum.Enum':
# Avoid noise
return []
s = info.dump(str_conv=self.str_conv,
type_str_conv=self.type_str_conv)
return s.splitlines()
示例3: make_type_info
def make_type_info(name: str,
is_abstract: bool = False,
mro: List[TypeInfo] = None,
bases: List[Instance] = None,
typevars: List[str] = None) -> TypeInfo:
"""Make a TypeInfo suitable for use in unit tests."""
class_def = ClassDef(name, Block([]), None, [])
class_def.fullname = name
if typevars:
v = [] # type: List[TypeVarDef]
id = 1
for n in typevars:
v.append(TypeVarDef(n, id, None))
id += 1
class_def.type_vars = v
info = TypeInfo(SymbolTable(), class_def)
if mro is None:
mro = []
info.mro = [info] + mro
if bases is None:
if mro:
# By default, assume that there is a single non-generic base.
bases = [Instance(mro[0], [])]
else:
bases = []
info.bases = bases
return info
示例4: type_object_type
def type_object_type(info: TypeInfo, builtin_type: Callable[[str], Instance]) -> Type:
"""Return the type of a type object.
For a generic type G with type variables T and S the type is generally of form
Callable[..., G[T, S]]
where ... are argument types for the __init__/__new__ method (without the self
argument). Also, the fallback type will be 'type' instead of 'function'.
"""
init_method = info.get_method('__init__')
if not init_method:
# Must be an invalid class definition.
return AnyType()
else:
fallback = builtin_type('builtins.type')
if init_method.info.fullname() == 'builtins.object':
# No non-default __init__ -> look at __new__ instead.
new_method = info.get_method('__new__')
if new_method and new_method.info.fullname() != 'builtins.object':
# Found one! Get signature from __new__.
return type_object_type_from_function(new_method, info, fallback)
# Both are defined by object. But if we've got a bogus
# base class, we can't know for sure, so check for that.
if info.fallback_to_any:
# Construct a universal callable as the prototype.
sig = CallableType(arg_types=[AnyType(), AnyType()],
arg_kinds=[ARG_STAR, ARG_STAR2],
arg_names=["_args", "_kwds"],
ret_type=AnyType(),
fallback=builtin_type('builtins.function'))
return class_callable(sig, info, fallback, None)
# Construct callable type based on signature of __init__. Adjust
# return type and insert type arguments.
return type_object_type_from_function(init_method, info, fallback)
示例5: visit_type_info
def visit_type_info(self, info: TypeInfo) -> None:
save_info = self.current_info
try:
self.current_info = info
if info.defn:
info.defn.accept(self)
if info.names:
self.visit_symbol_table(info.names)
if info.bases:
for base in info.bases:
base.accept(self.type_fixer)
if info._promote:
info._promote.accept(self.type_fixer)
if info.tuple_type:
info.tuple_type.accept(self.type_fixer)
if info.typeddict_type:
info.typeddict_type.accept(self.type_fixer)
if info.declared_metaclass:
info.declared_metaclass.accept(self.type_fixer)
if info.metaclass_type:
info.metaclass_type.accept(self.type_fixer)
if info._mro_refs:
info.mro = [lookup_qualified_typeinfo(self.modules, name, self.quick_and_dirty)
for name in info._mro_refs]
info._mro_refs = None
finally:
self.current_info = save_info
示例6: record_protocol_subtype_check
def record_protocol_subtype_check(left_type: TypeInfo, right_type: TypeInfo) -> None:
assert right_type.is_protocol
TypeState._rechecked_types.add(left_type)
TypeState._attempted_protocols.setdefault(
left_type.fullname(), set()).add(right_type.fullname())
TypeState._checked_against_members.setdefault(
left_type.fullname(),
set()).update(right_type.protocol_members)
示例7: anal_type_def
def anal_type_def(self, d):
self.check_no_global(d.name, d)
d.full_name = self.qualified_name(d.name)
info = TypeInfo({}, {}, d)
info.set_line(d.line)
self.types[d.full_name] = info
d.info = info
self.globals[d.name] = SymbolTableNode(GDEF, info, self.cur_mod_id)
示例8: base_class_definitions_incompatible
def base_class_definitions_incompatible(
self, name: str, base1: TypeInfo, base2: TypeInfo, context: Context
) -> None:
self.fail(
'Definition of "{}" in base class "{}" is incompatible '
'with definition in base class "{}"'.format(name, base1.name(), base2.name()),
context,
)
示例9: stale_info
def stale_info() -> TypeInfo:
suggestion = "<stale cache: consider running mypy without --quick>"
dummy_def = ClassDef(suggestion, Block([]))
dummy_def.fullname = suggestion
info = TypeInfo(SymbolTable(), dummy_def, "<stale>")
info.mro = [info]
info.bases = []
return info
示例10: add_info_hook
def add_info_hook(ctx) -> None:
class_def = ClassDef(ctx.name, Block([]))
class_def.fullname = ctx.api.qualified_name(ctx.name)
info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id)
class_def.info = info
obj = ctx.api.builtin_type('builtins.object')
info.mro = [info, obj.type]
info.bases = [obj]
ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))
info.metadata['magic'] = True
示例11: calculate_mro
def calculate_mro(info: TypeInfo, obj_type: Optional[Callable[[], Instance]] = None) -> None:
"""Calculate and set mro (method resolution order).
Raise MroError if cannot determine mro.
"""
mro = linearize_hierarchy(info, obj_type)
assert mro, "Could not produce a MRO at all for %s" % (info,)
info.mro = mro
# The property of falling back to Any is inherited.
info.fallback_to_any = any(baseinfo.fallback_to_any for baseinfo in info.mro)
TypeState.reset_all_subtype_caches_for(info)
示例12: missing_info
def missing_info(modules: Dict[str, MypyFile]) -> TypeInfo:
suggestion = "<missing info: *should* have gone away during fine-grained update>"
dummy_def = ClassDef(suggestion, Block([]))
dummy_def.fullname = suggestion
info = TypeInfo(SymbolTable(), dummy_def, "<missing>")
obj_type = lookup_qualified(modules, 'builtins.object', False)
assert isinstance(obj_type, TypeInfo)
info.bases = [Instance(obj_type, [])]
info.mro = [info, obj_type]
return info
示例13: stale_info
def stale_info(modules: Dict[str, MypyFile]) -> TypeInfo:
suggestion = "<stale cache: consider running mypy without --quick>"
dummy_def = ClassDef(suggestion, Block([]))
dummy_def.fullname = suggestion
info = TypeInfo(SymbolTable(), dummy_def, "<stale>")
obj_type = lookup_qualified(modules, 'builtins.object', False)
assert isinstance(obj_type, TypeInfo)
info.bases = [Instance(obj_type, [])]
info.mro = [info, obj_type]
return info
示例14: check_type_var_values
def check_type_var_values(self, type: TypeInfo, actuals: List[Type],
valids: List[Type], arg_number: int, context: Context) -> None:
for actual in actuals:
if (not isinstance(actual, AnyType) and
not any(is_same_type(actual, value) for value in valids)):
if len(actuals) > 1 or not isinstance(actual, Instance):
self.fail('Invalid type argument value for "{}"'.format(
type.name()), context)
else:
self.fail('Type argument {} of "{}" has incompatible value "{}"'.format(
arg_number, type.name(), actual.type.name()), context)
示例15: calculate_class_abstract_status
def calculate_class_abstract_status(typ: TypeInfo, is_stub_file: bool, errors: Errors) -> None:
"""Calculate abstract status of a class.
Set is_abstract of the type to True if the type has an unimplemented
abstract attribute. Also compute a list of abstract attributes.
Report error is required ABCMeta metaclass is missing.
"""
concrete = set() # type: Set[str]
abstract = [] # type: List[str]
abstract_in_this_class = [] # type: List[str]
for base in typ.mro:
for name, symnode in base.names.items():
node = symnode.node
if isinstance(node, OverloadedFuncDef):
# Unwrap an overloaded function definition. We can just
# check arbitrarily the first overload item. If the
# different items have a different abstract status, there
# should be an error reported elsewhere.
func = node.items[0] # type: Optional[Node]
else:
func = node
if isinstance(func, Decorator):
fdef = func.func
if fdef.is_abstract and name not in concrete:
typ.is_abstract = True
abstract.append(name)
if base is typ:
abstract_in_this_class.append(name)
elif isinstance(node, Var):
if node.is_abstract_var and name not in concrete:
typ.is_abstract = True
abstract.append(name)
if base is typ:
abstract_in_this_class.append(name)
concrete.add(name)
# In stubs, abstract classes need to be explicitly marked because it is too
# easy to accidentally leave a concrete class abstract by forgetting to
# implement some methods.
typ.abstract_attributes = sorted(abstract)
if is_stub_file:
if typ.declared_metaclass and typ.declared_metaclass.type.fullname() == 'abc.ABCMeta':
return
if typ.is_protocol:
return
if abstract and not abstract_in_this_class:
def report(message: str, severity: str) -> None:
errors.report(typ.line, typ.column, message, severity=severity)
attrs = ", ".join('"{}"'.format(attr) for attr in sorted(abstract))
report("Class {} has abstract attributes {}".format(typ.fullname(), attrs), 'error')
report("If it is meant to be abstract, add 'abc.ABCMeta' as an explicit metaclass",
'note')