Reputation: 670
I know, for example, that a function can be written to let know its argument is str
:
def myfunc(s: str) -> None:
I search the documentation of typing
but couldn't find anything about files as arguments.
How can I specify something as the following:
def use_file(a_file: ???) -> None:
where ???
is a binary file (as one created with open("data", "rb")
)?
Upvotes: 0
Views: 451
Reputation: 275
The typing
module provides specific types for file-like objects. Your question is a duplicate of this question.
from typing import IO, TextIO, BinaryIO
# Answer to the question
# If your function only accepts files opened in binary mode
def use_file(a_file: BinaryIO) -> None:
...
# If your function only accepts files opened in text mode
def use_file(a_file: TextIO) -> None:
...
# If your function accepts files opened in both modes
def use_file(a_file: IO) -> None:
...
Upvotes: 2