NamedTemporaryFile에 어떻게 주석을 달아야합니까?

Oct 19 2020

파일이나 파일과 같은 개체에 대한 유형 힌트typing.IO 에서 제안한대로 시도 했습니까? ,하지만 작동하지 않습니다.

from __future__ import annotations
from tempfile import NamedTemporaryFile
from typing import IO

def example(tmp: IO) -> str:
    print(tmp.file)
    return tmp.name


print(example(NamedTemporaryFile()))

이를 위해 mypy는 다음과 같이 말합니다.

test.py:6: error: "IO[Any]" has no attribute "file"; maybe "fileno"?

파이썬은 잘 실행됩니다. 그래서 코드는 괜찮습니다.

답변

4 Carcigenicate Oct 19 2020 at 21:15

나는 이것이 쉽게 타입 힌트 될 수 있다고 생각하지 않습니다.

의 정의를 확인하면 다음으로 NamedTemporaryFile끝나는 함수임을 알 수 있습니다.

return _TemporaryFileWrapper(file, name, delete)

그리고 _TemporaryFileWrapper다음과 같이 정의됩니다.

class _TemporaryFileWrapper:

즉, 표시 할 수있는 수퍼 클래스가 없으며 _TemporaryFileWrapper"모듈 전용"입니다. 또한 기존의 일부로 만드는 멤버가없는 것 같습니다 Protocol( Iterable및 제외하고 ContextManager여기에서는 해당 메서드를 사용하지 않음).

_TemporaryFileWrapper경고 를 사용 하고 무시 해야한다고 생각합니다 .

from tempfile import _TemporaryFileWrapper  # Weak error

def example(tmp: _TemporaryFileWrapper) -> str:
    print(tmp.file)
    return tmp.name

당신이 정말로 깨끗한 솔루션을 원한다면, 당신은 수있는 자신의 구현 Protocol (가) 당신이 필요로하는 속성을 포함하는, 또한 상속 한 Iterable과 ContextManager. 그런 다음 사용자 정의 Protocol.