Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
return overload_arg_similarity(actual.ret_type, formal.item)
else:
return 0
if isinstance(formal, Instance):
if isinstance(actual, CallableType):
actual = actual.fallback
if isinstance(actual, Overloaded):
actual = actual.items()[0].fallback
if isinstance(actual, TupleType):
actual = actual.fallback
if isinstance(actual, Instance):
# First perform a quick check (as an optimization) and fall back to generic
# subtyping algorithm if type promotions are possible (e.g., int vs. float).
if formal.type in actual.type.mro:
return 2
elif actual.type._promote and is_subtype(actual, formal):
return 1
else:
return 0
elif isinstance(actual, TypeType):
if formal.type.fullname() in {"builtins.object", "builtins.type"}:
return 2
else:
return 0
else:
return 0
if isinstance(actual, UnboundType) or isinstance(formal, UnboundType):
# Either actual or formal is the result of an error; shut up.
return 2
# Fall back to a conservative equality check for the remaining kinds of type.
return 2 if is_same_type(erasetype.erase_type(actual), erasetype.erase_type(formal)) else 0
def type_is_iterable(self, type: Type) -> bool:
return (is_subtype(type, self.named_generic_type('typing.Iterable',
[AnyType()])) and
isinstance(type, Instance))
if isinstance(s, NoneTyp) and not isinstance(t, NoneTyp):
s, t = t, s
if isinstance(s, UninhabitedType) and not isinstance(t, UninhabitedType):
s, t = t, s
value = t.accept(TypeJoinVisitor(s))
if value is None:
# XXX this code path probably should be avoided.
# It seems to happen when a line (x = y) is a type error, and
# it's not clear that assuming that x is arbitrary afterward
# is a good idea.
return declaration
if declaration is None or is_subtype(value, declaration):
return value
return declaration
def check_arg(self, caller_type: Type, original_caller_type: Type,
caller_kind: int,
callee_type: Type, n: int, m: int, callee: CallableType,
context: Context, messages: MessageBuilder) -> None:
"""Check the type of a single argument in a call."""
if isinstance(caller_type, DeletedType):
messages.deleted_as_rvalue(caller_type, context)
# Only non-abstract class can be given where Type[...] is expected...
elif (isinstance(caller_type, CallableType) and isinstance(callee_type, TypeType) and
caller_type.is_type_obj() and caller_type.type_object().is_abstract and
isinstance(callee_type.item, Instance) and callee_type.item.type.is_abstract and
# ...except for classmethod first argument
not caller_type.is_classmethod_class):
messages.fail("Only non-abstract class can be given where '{}' is expected"
.format(callee_type), context)
elif not is_subtype(caller_type, callee_type):
if self.chk.should_suppress_optional_error([caller_type, callee_type]):
return
messages.incompatible_argument(n, m, callee, original_caller_type,
caller_kind, context)
def is_valid_keyword_var_arg(self, typ: Type) -> bool:
"""Is a type valid as a **kwargs argument?"""
if self.chk.options.python_version[0] >= 3:
return is_subtype(typ, self.chk.named_generic_type(
'builtins.dict', [self.named_type('builtins.str'),
AnyType()]))
else:
return (
is_subtype(typ, self.chk.named_generic_type(
'builtins.dict',
[self.named_type('builtins.str'),
AnyType()]))
or
is_subtype(typ, self.chk.named_generic_type(
'builtins.dict',
[self.named_type('builtins.unicode'),
AnyType()])))
if isinstance(c_typ, Instance) and c_typ.last_known_value:
c_typ = c_typ.last_known_value
if isinstance(c_typ, LiteralType) and isinstance(c_typ.value, str):
if len(c_typ.value) != 1:
self.msg.requires_int_or_char(call, format_call=True)
if (not spec.type or spec.type == 's') and not spec.conversion:
if self.chk.options.python_version >= (3, 0):
if has_type_component(actual_type, 'builtins.bytes'):
self.msg.fail("On Python 3 '{}'.format(b'abc') produces \"b'abc'\";"
" use !r if this is a desired behavior", call,
code=codes.STR_BYTES_PY3)
if spec.flags:
numeric_types = UnionType([self.named_type('builtins.int'),
self.named_type('builtins.float')])
if (spec.type and spec.type not in NUMERIC_TYPES_NEW or
not spec.type and not is_subtype(actual_type, numeric_types) and
not custom_special_method(actual_type, '__format__')):
self.msg.fail('Numeric flags are only allowed for numeric types', call,
code=codes.STRING_FORMATTING)
def is_generator_return_type(self, typ: Type, is_coroutine: bool) -> bool:
"""Is `typ` a valid type for a generator/coroutine?
True if `typ` is a *supertype* of Generator or Awaitable.
Also true it it's *exactly* AwaitableGenerator (modulo type parameters).
"""
if is_coroutine:
# This means we're in Python 3.5 or later.
at = self.named_generic_type('typing.Awaitable', [AnyType()])
if is_subtype(at, typ):
return True
else:
gt = self.named_generic_type('typing.Generator', [AnyType(), AnyType(), AnyType()])
if is_subtype(gt, typ):
return True
return isinstance(typ, Instance) and typ.type.fullname() == 'typing.AwaitableGenerator'
def check_override(self, override: FunctionLike, original: FunctionLike,
name: str, name_in_super: str, supertype: str,
node: Context) -> None:
"""Check a method override with given signatures.
Arguments:
override: The signature of the overriding method.
original: The signature of the original supertype method.
name: The name of the subtype. This and the next argument are
only used for generating error messages.
supertype: The name of the supertype.
"""
# Use boolean variable to clarify code.
fail = False
if not is_subtype(override, original):
fail = True
elif (not isinstance(original, Overloaded) and
isinstance(override, Overloaded) and
name in nodes.reverse_op_methods.keys()):
# Operator method overrides cannot introduce overloading, as
# this could be unsafe with reverse operator methods.
fail = True
if fail:
emitted_msg = False
if (isinstance(override, CallableType) and
isinstance(original, CallableType) and
len(override.arg_types) == len(original.arg_types) and
override.min_args == original.min_args):
# Give more detailed messages for the common case of both
# signatures having the same number of arguments and no
# Type argument counts were checked in the main semantic analyzer pass. We assume
# that the counts are correct here.
info = t.type
for (i, arg), tvar in zip(enumerate(t.args), info.defn.type_vars):
if tvar.values:
if isinstance(arg, TypeVarType):
arg_values = arg.values
if not arg_values:
self.fail('Type variable "{}" not valid as type '
'argument value for "{}"'.format(
arg.name, info.name), t, code=codes.TYPE_VAR)
continue
else:
arg_values = [arg]
self.check_type_var_values(info, arg_values, tvar.name, tvar.values, i + 1, t)
if not is_subtype(arg, tvar.upper_bound):
self.fail('Type argument "{}" of "{}" must be '
'a subtype of "{}"'.format(
arg, info.name, tvar.upper_bound), t, code=codes.TYPE_VAR)
super().visit_instance(t)
left = left.fallback
right = right.fallback
else:
return False
elif isinstance(left, LiteralType):
left = left.fallback
elif isinstance(right, LiteralType):
right = right.fallback
# Finally, we handle the case where left and right are instances.
if isinstance(left, Instance) and isinstance(right, Instance):
# First we need to handle promotions and structural compatibility for instances
# that came as fallbacks, so simply call is_subtype() to avoid code duplication.
if (is_subtype(left, right, ignore_promotions=ignore_promotions)
or is_subtype(right, left, ignore_promotions=ignore_promotions)):
return True
# Two unrelated types cannot be partially overlapping: they're disjoint.
if left.type.has_base(right.type.fullname):
left = map_instance_to_supertype(left, right.type)
elif right.type.has_base(left.type.fullname):
right = map_instance_to_supertype(right, left.type)
else:
return False
if len(left.args) == len(right.args):
# Note: we don't really care about variance here, since the overlapping check
# is symmetric and since we want to return 'True' even for partial overlaps.
#
# For example, suppose we have two types Wrapper[Parent] and Wrapper[Child].
# It doesn't matter whether Wrapper is covariant or contravariant since