本文整理汇总了Python中mypy.nodes.TypeInfo类的典型用法代码示例。如果您正苦于以下问题:Python TypeInfo类的具体用法?Python TypeInfo怎么用?Python TypeInfo使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TypeInfo类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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__'))
开发者ID:sixolet,项目名称:mypy,代码行数:26,代码来源:deps.py
示例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()
开发者ID:Michael0x2a,项目名称:mypy,代码行数:7,代码来源:testmerge.py
示例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
开发者ID:akaihola,项目名称:mypy,代码行数:31,代码来源:typefixture.py
示例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)
开发者ID:rowillia,项目名称:mypy,代码行数:35,代码来源:checkmember.py
示例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
开发者ID:mananpal1997,项目名称:mypy,代码行数:27,代码来源:fixup.py
示例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)
开发者ID:Michael0x2a,项目名称:mypy,代码行数:8,代码来源:typestate.py
示例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)
开发者ID:SRiikonen,项目名称:mypy-py,代码行数:8,代码来源:semanal.py
示例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,
)
开发者ID:judasnow,项目名称:mypy,代码行数:8,代码来源:messages.py
示例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
开发者ID:greatmazinger,项目名称:mypy,代码行数:9,代码来源:fixup.py
示例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
开发者ID:Michael0x2a,项目名称:mypy,代码行数:11,代码来源:common_api_incremental.py
示例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)
开发者ID:Michael0x2a,项目名称:mypy,代码行数:11,代码来源:mro.py
示例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
开发者ID:python,项目名称:mypy,代码行数:11,代码来源:fixup.py
示例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
开发者ID:sixolet,项目名称:mypy,代码行数:11,代码来源:fixup.py
示例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)
开发者ID:alexandrul,项目名称:mypy,代码行数:11,代码来源:typeanal.py
示例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')
开发者ID:mananpal1997,项目名称:mypy,代码行数:52,代码来源:semanal_classprop.py
示例16: visit_class_def
def visit_class_def(self, cdef: ClassDef) -> None:
kind = self.kind_by_scope()
if kind == LDEF:
return
elif kind == GDEF:
self.sem.check_no_global(cdef.name, cdef)
cdef.fullname = self.sem.qualified_name(cdef.name)
info = TypeInfo(SymbolTable(), cdef, self.sem.cur_mod_id)
info.set_line(cdef.line, cdef.column)
cdef.info = info
if kind == GDEF:
self.sem.globals[cdef.name] = SymbolTableNode(kind, info)
self.process_nested_classes(cdef)
开发者ID:sixolet,项目名称:mypy,代码行数:13,代码来源:semanal_pass1.py
示例17: 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'.
"""
# We take the type from whichever of __init__ and __new__ is first
# in the MRO, preferring __init__ if there is a tie.
init_method = info.get_method('__init__')
new_method = info.get_method('__new__')
if not init_method:
# Must be an invalid class definition.
return AnyType(TypeOfAny.from_error)
# There *should* always be a __new__ method except the test stubs
# lack it, so just copy init_method in that situation
new_method = new_method or init_method
init_index = info.mro.index(init_method.info)
new_index = info.mro.index(new_method.info)
fallback = info.metaclass_type or builtin_type('builtins.type')
if init_index < new_index:
method = init_method
elif init_index > new_index:
method = new_method
else:
if init_method.info.fullname() == 'builtins.object':
# 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.
any_type = AnyType(TypeOfAny.special_form)
sig = CallableType(arg_types=[any_type, any_type],
arg_kinds=[ARG_STAR, ARG_STAR2],
arg_names=["_args", "_kwds"],
ret_type=any_type,
fallback=builtin_type('builtins.function'))
return class_callable(sig, info, fallback, None)
# Otherwise prefer __init__ in a tie. It isn't clear that this
# is the right thing, but __new__ caused problems with
# typeshed (#5647).
method = init_method
# Construct callable type based on signature of __init__. Adjust
# return type and insert type arguments.
return type_object_type_from_function(method, info, fallback)
开发者ID:Michael0x2a,项目名称:mypy,代码行数:51,代码来源:checkmember.py
示例18: check_type_var_values
def check_type_var_values(self, type: TypeInfo, actuals: List[Type], arg_name: str,
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:
class_name = '"{}"'.format(type.name())
actual_type_name = '"{}"'.format(actual.type.name())
self.fail(messages.INCOMPATIBLE_TYPEVAR_VALUE.format(
arg_name, class_name, actual_type_name), context)
开发者ID:sixolet,项目名称:mypy,代码行数:14,代码来源:semanal_pass3.py
示例19: process_type_info
def process_type_info(self, info: TypeInfo) -> None:
# TODO additional things like the MRO
replace_nodes_in_symbol_table(info.names, self.replacements)
for i, item in enumerate(info.mro):
info.mro[i] = self.fixup(info.mro[i])
for i, base in enumerate(info.bases):
self.fixup_type(info.bases[i])
开发者ID:greatmazinger,项目名称:mypy,代码行数:7,代码来源:astmerge.py
示例20: save_namedtuple_body
def save_namedtuple_body(self, named_tuple_info: TypeInfo) -> Iterator[None]:
"""Preserve the generated body of class-based named tuple and then restore it.
Temporarily clear the names dict so we don't get errors about duplicate names
that were already set in build_namedtuple_typeinfo (we already added the tuple
field names while generating the TypeInfo, and actual duplicates are
already reported).
"""
nt_names = named_tuple_info.names
named_tuple_info.names = SymbolTable()
yield
# Make sure we didn't use illegal names, then reset the names in the typeinfo.
for prohibited in NAMEDTUPLE_PROHIBITED_NAMES:
if prohibited in named_tuple_info.names:
if nt_names.get(prohibited) is named_tuple_info.names[prohibited]:
continue
ctx = named_tuple_info.names[prohibited].node
assert ctx is not None
self.fail('Cannot overwrite NamedTuple attribute "{}"'.format(prohibited),
ctx)
# Restore the names in the original symbol table. This ensures that the symbol
# table contains the field objects created by build_namedtuple_typeinfo. Exclude
# __doc__, which can legally be overwritten by the class.
named_tuple_info.names.update({
key: value for key, value in nt_names.items()
if key not in named_tuple_info.names or key != '__doc__'
})
开发者ID:Michael0x2a,项目名称:mypy,代码行数:30,代码来源:semanal_namedtuple.py
注:本文中的mypy.nodes.TypeInfo类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论