Skip to content

What to do about inferring types from multiple scopes? #4492

Closed
@JukkaL

Description

@JukkaL

Typically mypy infers the type of the variable from the first assignment. In some cases mypy infers the type from two assignments. The first assignment creates internally a partial type, which is missing some information. The second assignment completes the type. Example:

x = []  # x gets a partial List type
x.append(1)  # x gets complete type List[int]

In some cases the assignments can be in two different scopes. Example:

x = []

def f() -> None:
    x.append(1)

# type of x is List[int]

This feature has apparently been supported a while, but it has some issues:

There are a few alternatives which might be reasonable, instead of the current behavior:

  1. Require an annotation for the variable in cases such as the above, where the assignment that completes a partial type is in a different scope. This would break compatibility with previous mypy releases. Based on a quick experiment, the S internal codebase at Dropbox would require about 40 additional type annotations if we make this change.
  2. Ignore assignments in nested scopes and assume Any for any missing partial type information. For example, if the initial assignment is x = [] and the only additional assignments are in nested scopes, infer List[Any] as the type of x. This way the type of x is defined entirely by the contents of a single scope, which solves the above problems. This also introduces an additional problem -- implicit Any types. We might want to have a strictness flag that falls back to requiring a type annotation (as in option 1 above).

Currently my biggest concern is fine-grained incremental mode. There it may be possible to support the current behavior by introducing a new concept: "bound targets". I'll add a writeup about this to #4464.

@gvanrossum @msullivan @ilevkivskyi Thoughts?

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions