Reusing variable name in different scopes
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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]]
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the test.py reproducer and the main function shown in the issue, then trace how mypy infers types for var across the if and else branches. Done means the example produces no incompatible-assignment or setitem errors and the return is treated as Union[Dict[str, str], List[str]].
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100