python / python/mypy

Reusing variable name in different scopes

オープン
#5,750 コメント 5 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

false-positive priority-1-normal topic-union-types topic-usability
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

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]]

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず test.py の再現コードと issue に示されている main 関数から始め、次に if ブランチと else ブランチを通じて mypy が var の型をどのように推論するかを追跡します。例で incompatible-assignment エラーも setitem エラーも発生せず、戻り値が Union[Dict[str, str], List[str]] として扱われれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。