Skip to content

Tight type scoping for loop local variables #19504

@suhasdotcom

Description

@suhasdotcom

Feature

Hi Team,

I am not sure whether this is a bug or mypy just supporting the native python typing, but, this seems like a good add-on to tight type scoping for variables introduced in a loop local setting.

Check this Playground link.

Here, the scope (specifically, typing scope for mypy) of variable key should be valid only for the current loop, but it goes beyond the loop:

def loop_builtin_type_infer_issue() -> None:
    int_keys: list[int] = [1] # only one item included for brevity
    for key in int_keys:    # key is int here, correct
        print(key)

    str_keys: list[str] = ['no_all'] # only one item included for brevity
    for key in str_keys:    # <-- this is the problem area.
                            # mypy treats key as int here as well, taking 
                            # the key type from the previous loop. When it should actually infer the type of key here 
                            # as str, not int.
        print(key)

Error encountered:

main.py:20: error: Incompatible types in assignment (expression has type "str", variable has type "int")  [assignment]

I guess if a variable is introduced in a loop then mypy should (unlike python typing) treat its type scoped to that loop and thus the type of key in the second loop should be str not int carried on from the previous loop.

I haven't raised it as a bug as I am not entirely sure whether this is a bug and hence, am raising it as a feature.

Please let me know your thoughts.

Pitch

Introducing this feature will make programming with loop local introduced variables more pragmatic.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy