Skip to content

How to annotate variables? #9

@gvanrossum

Description

@gvanrossum

In mypy there are two ways to annotate a variable: with a # type: comment or a cast expression. The following are equivalent from mypy's POV:

    result = []  # type: List[int]
    result = List[int]()

Each has its disadvantages:

  • Jython's parser doesn't preserve comments and they don't want to change the parser
  • The cast expression incurs significant overhead (List[int] creates a new parametrize type object)

There's no clear solution at this point; something has got to give (though the PEP should probably support both and point out the issues).

For some specific cases (e.g. a variable initialized to an empty concrete container that is used directly in a 'return' statement) we may be able to improve the type inferencer, but in general that's a path we would rather not take (there's a good reason we start with function annotations only).

In the future (e.g. Python 3.6 or later) we may be confident enough to introduce variable annotations, e.g.

var result: List[int] = []

or perhaps even

result: List[int] = []

But this remains to be seen, and we definitely don't want to do this for the current PEP or Python 3.5. Plus, it might still incur exactly the same runtime overhead.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions