Search code examples
pythoniotypingmypy

Convert string to IO[str] data type


I have following problem.

For my unit tests purpose, I'm generating the path to the resource file this way:

file_name = os.path.join(
        os.path.dirname(os.path.abspath(__file__)), 'resources/resource.json'
    )

Returned data type of file_name var is a str.

The method, which I'm testing by this unit test, then accept IO[str] data type from typing library.

Unit test is working, but when I run mypy validation on my code, I'm getting following error message:

tests/test_get_requirements.py:73: error: Argument 1 to "JiraRequirements" has incompatible type "str"; expected "IO[str]"

Line **73** is basically the instantiation of new object of *JiraRequirements class*

MockedObject = JiraRequirements(file_name)

Solution

  • The mypy error is correct. You pass str filename where typing expects an opened file object. From IO docs:

    This is an abstract, generic version of the return of open().