Skip to content

Reusing variable name in different scopes #5750

Open
@takeda

Description

@takeda

I saw that there is a similar bug around redefining a variable, but I believe this one is slightly different problem, here is the code:

#! /usr/bin/env python

from typing import Dict, List, Union

def main(arg):
	# type: (bool) -> Union[Dict[str, str], List[str]]

	if arg:
		var = list()
		var.append('something')
	else:
		var = dict()
		var['key'] = 'something'

	return var


if __name__ == '__main__':
	main(True)

The variable var while it uses the same name, it is technically a different variable, but mypy 0.630 is complaining about it:

$ ../py37/bin/mypy --python-executable ../py27/bin/python test.py
test.py:12: error: Incompatible types in assignment (expression has type "Dict[<nothing>, <nothing>]", variable has type "List[str]")
test.py:13: error: No overload variant of "__setitem__" of "list" matches argument types "str", "str"
test.py:13: note: Possible overload variants:
test.py:13: note:     def __setitem__(self, int, str) -> None
test.py:13: note:     def __setitem__(self, slice, Iterable[str]) -> None

Ideally it should have no problem with it and at the point where there is return statement it should just do an union so the type would be Union[Dict[str, str], List[str]]

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions