3

Python 2 は、状況によっては暗黙的に に変換strされます。この変換は、結果の値で何をしようとしているかによって、 をunicodeスローすることがあります。UnicodeError正確なセマンティクスはわかりませんが、避けたいものです。

この暗黙の変換を使用するプログラムを引き起こすために、別のタイプまたは( http://mypy-lang.blogspot.co.uk/2016/07/mypy-043-released.htmlunicode ) に似たコマンドライン引数を使用することは可能ですか?タイプチェックに失敗するには?--strict-optional

def returns_string_not_unicode():
    # type: () -> str
    return u"a"

def returns_unicode_not_string():
    # type: () -> unicode
    return "a"

この例では、関数のみreturns_string_not_unicodeが型チェックに失敗しています。

$ mypy --py2 unicode.py
unicode.py: note: In function "returns_string_not_unicode":
unicode.py:3: error: Incompatible return value type (got "unicode", expected "str")

両方とも型チェックに失敗することを望みます。

編集:

type: () -> byteと同じように扱われているようです。str

def returns_string_not_unicode():
    # type: () -> bytes
    return u"a"
4

1 に答える 1