scribu
scribu

Reputation: 3078

Python type hints: How to specify file pointer as an argument?

I'm writing a function that takes a file pointer as an argument and writes to it. And I want to add a type hint to that argument:

def write_some_stuff(fp: _io.TextIOWrapper):
    ...

_io.TextIOWrapper is what type(open(...)) gives me.

Is there something else I should use?

Upvotes: 8

Views: 4684

Answers (2)

klamann
klamann

Reputation: 1817

You should use the typing module, which was introduced in Python 3.5: typing.TextIO fits best in this case.

Generic type IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open().

In your example:

from typing import TextIO

def write_some_stuff(fp: TextIO):
    ...

Upvotes: 9

Blckknght
Blckknght

Reputation: 104712

If you want to be a little more generic and allow any file object that is in text mode (i.e. read() returns Unicode strings), you probably want to hint that you take an io.TextIOBase argument. That will allow instances of io.StringIO in addition to the more common io.TextIOWrapper instances.

You also don't need the underscore on the io module's name, even if you stick with TextIOWrapper. The regular io module imports all relevant types from the _io module into its own namespace.

Upvotes: 3

Related Questions