Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def default(self, typ: Type) -> ProperType:
typ = get_proper_type(typ)
if isinstance(typ, Instance):
return object_from_instance(typ)
elif isinstance(typ, UnboundType):
return AnyType(TypeOfAny.special_form)
elif isinstance(typ, TupleType):
return self.default(mypy.typeops.tuple_fallback(typ))
elif isinstance(typ, TypedDictType):
return self.default(typ.fallback)
elif isinstance(typ, FunctionLike):
return self.default(typ.fallback)
elif isinstance(typ, TypeVarType):
return self.default(typ.upper_bound)
else:
return AnyType(TypeOfAny.special_form)
def calculate_return_type(expr: Expression) -> Optional[Type]:
"""Return the return type if we can calculate it.
This only uses information available during semantic analysis so this
will sometimes return None because of insufficient information (as
type inference hasn't run yet).
"""
if isinstance(expr, RefExpr):
if isinstance(expr.node, FuncDef):
typ = expr.node.type
if typ is None:
# No signature -> default to Any.
return AnyType(TypeOfAny.unannotated)
# Explicit Any return?
if isinstance(typ, CallableType):
return typ.ret_type
return None
elif isinstance(expr.node, Var):
return expr.node.type
elif isinstance(expr, CallExpr):
return calculate_return_type(expr.callee)
return None
super().__init__(line, column)
self.type_of_any = type_of_any
# If this Any was created as a result of interacting with another 'Any', record the source
# and use it in reports.
self.source_any = source_any
if source_any and source_any.source_any:
self.source_any = source_any.source_any
if source_any is None:
self.missing_import_name = missing_import_name
else:
self.missing_import_name = source_any.missing_import_name
# Only unimported type anys and anys from other anys should have an import name
assert (missing_import_name is None or
type_of_any in (TypeOfAny.from_unimported_type, TypeOfAny.from_another_any))
# Only Anys that come from another Any can have source_any.
assert type_of_any != TypeOfAny.from_another_any or source_any is not None
# We should not have chains of Anys.
assert not self.source_any or self.source_any.type_of_any != TypeOfAny.from_another_any
def add_metadata_var(api: SemanticAnalyzerPluginInterface, info: TypeInfo) -> None:
"""Add .metadata attribute to a declarative base."""
sym = api.lookup_fully_qualified_or_none('sqlalchemy.sql.schema.MetaData')
if sym:
assert isinstance(sym.node, TypeInfo)
typ = Instance(sym.node, []) # type: Type
else:
typ = AnyType(TypeOfAny.special_form)
add_var_to_class('metadata', typ, info)
if field_info is None:
return AnyType(TypeOfAny.unannotated)
is_nullable = self.get_field_nullability(field, method)
if isinstance(field, RelatedField):
related_model_cls = self.get_field_related_model_cls(field)
if related_model_cls is None:
return AnyType(TypeOfAny.from_error)
if method == 'values':
primary_key_field = self.get_primary_key_field(related_model_cls)
return self.get_field_get_type(api, primary_key_field, method=method)
model_info = helpers.lookup_class_typeinfo(api, related_model_cls)
if model_info is None:
return AnyType(TypeOfAny.unannotated)
return Instance(model_info, [])
else:
return helpers.get_private_descriptor_type(field_info, '_pyi_private_get_type',
is_nullable=is_nullable)
return self.check_overload_call(callee=callee,
args=args,
arg_types=arg_types,
arg_kinds=arg_kinds,
arg_names=arg_names,
callable_name=callable_name,
object_type=object_type,
context=context,
arg_messages=arg_messages)
elif isinstance(callee, AnyType) or not self.chk.in_checked_function():
self.infer_arg_types_in_empty_context(args)
if isinstance(callee, AnyType):
return (AnyType(TypeOfAny.from_another_any, source_any=callee),
AnyType(TypeOfAny.from_another_any, source_any=callee))
else:
return AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form)
elif isinstance(callee, UnionType):
self.msg.disable_type_names += 1
results = [self.check_call(subtype, args, arg_kinds, context, arg_names,
arg_messages=arg_messages)
for subtype in callee.relevant_items()]
self.msg.disable_type_names -= 1
return (UnionType.make_simplified_union([res[0] for res in results]),
callee)
elif isinstance(callee, Instance):
call_function = analyze_member_access('__call__', callee, context,
False, False, False, self.named_type,
self.not_ready_callback, self.msg,
original_type=callee, chk=self.chk)
return self.check_call(call_function, args, arg_kinds, context, arg_names,
callable_node, arg_messages)
elif isinstance(callee, TypeVarType):
def typed_dict_delitem_callback(ctx: MethodContext) -> Type:
"""Type check TypedDict.__delitem__."""
if (isinstance(ctx.type, TypedDictType)
and len(ctx.arg_types) == 1
and len(ctx.arg_types[0]) == 1):
keys = try_getting_str_literals(ctx.args[0][0], ctx.arg_types[0][0])
if keys is None:
ctx.api.fail(message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL, ctx.context)
return AnyType(TypeOfAny.from_error)
for key in keys:
if key in ctx.type.required_keys:
ctx.api.msg.typeddict_key_cannot_be_deleted(ctx.type, key, ctx.context)
elif key not in ctx.type.items:
ctx.api.msg.typeddict_key_not_found(ctx.type, key, ctx.context)
return ctx.default_return_type
semanal_api = helpers.get_semanal_api(ctx)
callee = ctx.call.callee
assert isinstance(callee, MemberExpr)
assert isinstance(callee.expr, RefExpr)
base_manager_info = callee.expr.node
if base_manager_info is None:
if not semanal_api.final_iteration:
semanal_api.defer()
return
assert isinstance(base_manager_info, TypeInfo)
new_manager_info = semanal_api.basic_new_typeinfo(ctx.name,
basetype_or_fallback=Instance(base_manager_info,
[AnyType(TypeOfAny.unannotated)]))
new_manager_info.line = ctx.call.line
new_manager_info.defn.line = ctx.call.line
new_manager_info.metaclass_type = new_manager_info.calculate_metaclass_type()
current_module = semanal_api.cur_mod_node
current_module.names[ctx.name] = SymbolTableNode(GDEF, new_manager_info,
plugin_generated=True)
passed_queryset = ctx.call.args[0]
assert isinstance(passed_queryset, NameExpr)
derived_queryset_fullname = passed_queryset.fullname
assert derived_queryset_fullname is not None
sym = semanal_api.lookup_fully_qualified_or_none(derived_queryset_fullname)
assert sym is not None
if sym.node is None:
d.accept(self)
if isinstance(d, AssertStmt) and assert_will_always_fail(d, options):
# We've encountered an assert that's always false,
# e.g. assert sys.platform == 'lol'. Truncate the
# list of statements. This mutates file.defs too.
del defs[i + 1:]
break
# Add implicit definition of literals/keywords to builtins, as we
# cannot define a variable with them explicitly.
if mod_id == 'builtins':
literal_types = [
('None', NoneType()),
# reveal_type is a mypy-only function that gives an error with
# the type of its arg.
('reveal_type', AnyType(TypeOfAny.special_form)),
# reveal_locals is a mypy-only function that gives an error with the types of
# locals
('reveal_locals', AnyType(TypeOfAny.special_form)),
] # type: List[Tuple[str, Type]]
# TODO(ddfisher): This guard is only needed because mypy defines
# fake builtins for its tests which often don't define bool. If
# mypy is fast enough that we no longer need those, this
# conditional check should be removed.
if 'bool' in self.sem.globals:
bool_type = self.sem.named_type('bool')
literal_types.extend([
('True', bool_type),
('False', bool_type),
('__debug__', bool_type),
])
def set_first_generic_param_as_default_for_second(fullname: str, ctx: AnalyzeTypeContext) -> Type:
if not ctx.type.args:
try:
return ctx.api.named_type(fullname, [AnyType(TypeOfAny.explicit),
AnyType(TypeOfAny.explicit)])
except KeyError:
# really should never happen
return AnyType(TypeOfAny.explicit)
args = ctx.type.args
if len(args) == 1:
args = [args[0], args[0]]
analyzed_args = [ctx.api.analyze_type(arg) for arg in args]
try:
return ctx.api.named_type(fullname, analyzed_args)
except KeyError:
# really should never happen
return AnyType(TypeOfAny.explicit)