[Python-ideas] ideas for type hints for variable: beyond comments

Nick Coghlan ncoghlan at gmail.com
Wed Sep 2 06:01:25 CEST 2015

On 1 September 2015 at 23:03, Steven D'Aprano <steve at pearwood.info> wrote:
> PEP 484 says:
> "No first-class syntax support for explicitly marking variables as being
> of a specific type is added by this PEP. To help with type inference in
> complex cases, a comment of the following format may be used: ..."
> https://www.python.org/dev/peps/pep-0484/
> I recall that in the discussions prior to the PEP, I got the strong
> impression that Guido was open to the concept of annotating variables in
> principle, but didn't think it was very important (for the most part,
> the type checker should be able to infer the variable type), and he
> didn't want to delay the PEP for the sake of agreement on a variable
> declaration syntax when a simple comment will do the job.
> So in principle, if we agree that type declarations for variables should
> look like (let's say) `str s = some_function(arg)` then the syntax may
> be added in the future, but it's a low priority.

The main case where it's potentially useful is when we want to
initialise a variable to None, but constrain permitted rebindings
(from a typechecker's perspective) to a particular type. When we
initialise a variable to an actual value, then type inference can
usually handle it.

Using the typing module as it exists today, I believe this should work
for that purpose (although I haven't actually tried it with mypy or
any other typechecker):

    from typing import TypeVar, Generic, Optional

    T = TypeVar("T")

    class Var(Generic[T]):
        def __new__(cls, value:Optional[T] = None) -> Optional[T]:
            return None

    i = Var[int]()

Unless I've misunderstood the likely outcome of type inference
completely, the value of i here will be None, but it's inferred type
would be Optional[int]. At runtime, you could still rebind "i" to
whatever you want, but a typechecker would complain if it was to
anything other than None or an integer.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list