Typing: Allow Ellipsis as annotation for inferred type

Created on 3 Sep 2016  路  8Comments  路  Source: python/typing

PEP 484 says that if an annotation is missing then the type assumed to be Any

def f(x) -> None:
    reveal_type(x) # Revealed type is 'Any'
def g(x: int):
    pass
reveal_type(g(1)) # Revealed type is 'Any'

However, it is not clear how to say to type checker that it should infer a missing type, rather than assume that it is Any. It was proposed by @ncoghlan to use Ellipsis for this purpose:

def f(x: ...) -> None:
    ...
def g(x: int) -> ...:
    ...

I am opening this issue, so that this idea will not be forgotten.

Most helpful comment

BTW in PyCharm we just infer types for values that are missing (thus not conforming formally to PEP 484).

All 8 comments

This kind of inference could be very costly -- you may have to trace
arbitrary many calls deep.

The checker could still give up and use Any if inference proved too difficult, though. From the PEP 525 discussions, the main places where it seemed like this could be useful is to allow type inference on instance variables while still declaring them in the class body, allowing a function's return type to be implied by the return statements it contains, as well as allowing an implied Union for types initialised conditionally:

x: ...
if initial_values is not None:
    x = list(initial_values)
else:
    x = None
# x would be considered Optional[List[Any]] here, or potentially a more specific type if the inference engine has a more precise type for initial_values than Iterable[Any]

I don't have any insight into how practical that kind of thing would be to implement, though.

def f(x: ...) -> None:
Assumes that you can infer an accurate call graph, which is highly unlikely.
In general, attempting infer types globally, which is required to infer parameter types, is highly inaccurate.

Maybe we could still allow the second form (with Nick's addition about inference cost)?

def g(x: int) -> ...:
    return x
reveal_type(g(1)) # Revealed type is 'Any'

I think this is something where we should first come up with an
experimental implementation (maybe a flag for mypy) before we decide to
modify PEP 484. (And what should get_type_hints() do?)

@gvanrossum
I agree there is no hurry for this. I just wanted to open an issue so that this idea will not be forgotten.

BTW in PyCharm we just infer types for values that are missing (thus not conforming formally to PEP 484).

Or use pytype to generate the type information. ;)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

shoyer picture shoyer  路  8Comments

zsluedem picture zsluedem  路  3Comments

max-sixty picture max-sixty  路  7Comments

Phlogistique picture Phlogistique  路  4Comments

gvanrossum picture gvanrossum  路  8Comments