-
Notifications
You must be signed in to change notification settings - Fork 249
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
a way to refer to overloaded functions #623
Comments
You can probably do this with a Protocol with an overloaded |
Can you be more specific? Do you mean something like the following? from typing import overload, TypeVar, Generic, Callable, Union, Protocol
A = TypeVar('A', covariant=True)
B = TypeVar('B', covariant=True)
S = TypeVar('S', contravariant=True)
T = TypeVar('T', contravariant=True)
class P(Protocol[S, T, A, B]):
@overload
def __call__(self, x):
# type: (S) -> A
pass
@overload
def __call__(self, x):
# type: (T) -> B
pass
class Spam(Generic[A, B]):
def __init__(self, a, b):
# type: (A, B) -> None
self.a = a
self.b = b
def map(self, f, g):
# type: (Callable[[A], S], Callable[[B], T]) -> Spam[S, T]
return Spam(f(self.a), g(self.b))
def mapone(self, f):
# type: (P) -> Spam[S, T]
return self.map(f, f)
@overload
def eggs(x):
# type: (int) -> str
pass
@overload
def eggs(x):
# type: (str) -> bool
pass
def eggs(x):
return str(x) if isinstance(x, int) else False
f = Spam(1, "1")
g = f.mapone(eggs)
reveal_type(g) because:
|
lol I didn't provide parameters to |
ye gods, it works, once I update |
Callback protocols is a recommended way of expressing this, and other tricky callbacks, see https://mypy.readthedocs.io/en/latest/protocols.html#callback-protocols |
Is there a way to refer to overloaded functions in argument position? It seems as if there isn't;
reveal_type
displays such functions asOverload(…)
, but there is noOverload
exported fromtyping
ortyping_extensions
.My use case is generic functions:
from typing import overload, TypeVar, Generic, Callable, Union, cast
Given this:
I want to be able to do:
But this doesn't work. Although mypy recognizes that
eggs
is both a functionstr -> bool
and a functionint -> str
, and the following typechecks:, giving
mapone
the typeUnion[Callable[[A], S], Callable[[B], T]] -> Spam[S, T]
requires me to give a type annotation to the second line here:and types
g
asAny
. Any type annotation I give is accepted.Giving
mapone
the alternative annotationCallable[[Union[A, B]], Union[S, T]] -> Spam[S, T]
gives the errorArgument 1 to "mapone" of "Spam" has incompatible type overloaded function; expected "Callable[[Union[str, int]], <nothing>]"
(Come to think of it, if it were possible to refer to overloaded functions in argument position like this, it would probably also be possible just to use
Overload
or whatever in the initial annotation of overloaded functions and avoid the repeated names, but that is a separate thing, I suppose.)The text was updated successfully, but these errors were encountered: