-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
A possible syntax for a function type with a varargs argument list #540
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
Comments
Something like this would be useful. See also #393; If we want go a bit further, we could have a special kind of type variable that matches any function argument signature. This would let use represent additional things, such as a function that maps any function to the same function but with a Args = Var('Args', kind='args')
def nonefy(func: Callable[Args, Any]) -> Callable[Args, None]: ...
def f(x: int) -> int:
print(x)
return x
g = nonefy(f) # This has type Callable[[int], None] (but it also accepts a keyword arg) An additional refinement would allow a type variable that maps to a variable-length list of types (unlike the above proposal, it wouldn't know about keyword arguments etc.), and this variable could also be used in TL = Var('TL', kind='typelist')
X = Var('X')
def f(f: Callable[TL, X], t: Tuple[TL]) -> X: # Or Callable[[TL], X]
return f(*t) # OK!
c = f(chr, (32,)) # Okay, type of c is str
f(pow, (2, 3)) # Okay
f(pow, (2,)) # Error At least the latter would probably be useful for higher-order functions. |
Hm... The use cases for your Args typevar seem meager, and the TL looks confusingly like a function of one arg. (Especially Instead, let's have a predefined name AnyArgs that can be used instead of a list of argument types, e.g. |
Was the use of ellipsis considered?
|
Ah, I actually like Callable[..., int]. I can't recall if it was considered before or not (I think we only rejected None and Any, because both are valid types (None being a shortcut for NoneType) and Callable[Any, int] looks like a typo for Callable[[Any], int]. Jukka, what do you think? Does Callable[..., int] work for mypy? |
I like |
Fortunately that's also valid Python 2 syntax (in Python 2 it's only valid in a Let's call this settled then. |
Cool, I didn't remember that :-) |
Closing as this is a dupe of #393. |
I just skimmed the README for Reticulated Python (https://github.com/mvitousek/reticulated). They have a useful hack to spell the type of a function with varargs or other dynamic hacks in the argument list: a normal function type is spelled e.g. Function([Int, Int], Float); a function type with a varargs argument list is spelled e.g. Function(DynParameters, Float). In mypy this would be Function[DynParameters, float]. (Or pick some other name for DynParameters.)
The text was updated successfully, but these errors were encountered: