Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Type Annotations, how to define elements of a tuple?

Here is a minimal case.

def foo(x:int, y:int) -> tuple: 
    return (x*y, y//2)

It's very tempting to be able to write -> tuple(:int, :int) which is not a valid format. Is there a correct approach in this case, or is it still a gray area until python moves further down the type annotation road?

edit: It's apparently possible to do something of the like

def bar(x, y) -> ((str, int), (str, int)): 
     return ("%s+%s" %(x,y), x+y), ("%s-%s" %(x,y), x-y) 
like image 291
user3467349 Avatar asked Jan 30 '15 18:01

user3467349


1 Answers

There is now a way to annotate this case:

from typing import Tuple
def foo(x:int, y:int) -> Tuple[int, int]: 
    return (x*y, y//2)

Note: python run-time won't complain about -> (int, int), but it is not correct type annotation according to PEP 484. In other words, you can use it if you want to create your a mini-language using type hints for your own purposes; but it's not accepted by the python typing standard (PEP 484).

like image 141
max Avatar answered Sep 22 '22 11:09

max