Skip to content

Bug? Inconsistent type inference between open() and Path().open() #6666

Closed

Description

@BuongiornoTexas

After spending quite a while one this, I'm not sure if this is an intended mode of operation, a mypy issue or a typeshed issue. If I have this in the wrong place or if it is not an issue, please close and I will re-raise in typeshed if appropriate.

I have run into an issue with inconsistent type-inferences for open() and pathlib.Path().open().

#!/usr/bin/env python3

from pathlib import Path
fp = open('README.rst', 'rt')
print(type(fp))
fp1 = Path('README.rst').open('rt')
print(type(fp1))

yields:

<class '_io.TextIOWrapper'>
<class '_io.TextIOWrapper'>

However, running mypy reveal_type on fp and fp1 yields:

Revealed type is 'typing.TextIO'
Revealed type is 'typing.IO[Any]'

I would expect both of these to reveal typing.TextIO. I found this issue when using a routine that switched TextIO output between sys.stdout (TextIO) and a file opened with Path().open() (IO).

This is on python 3.7.2 and mypy 0.700 with arguments: --follow-imports=silent, --show-column-numbers, --disallow-untyped-defs.

Activity

  1. gvanrossum commented on Apr 12, 2019

    @gvanrossum
    Member

    Right now we have a plugin that special-cases builtins.open() but not Path.open(). This should be solved in typeshed by making the definition of Path.open() overloaded on various Literal types. So I am closing this as "not a mypy bug" but I recommend that you submit a PR to typeshed to add this.

  2. BuongiornoTexas commented on Apr 12, 2019

    @BuongiornoTexas
    Author

    Thanks. Will do.

    I figured with an issue number of 6666, this was always going to be short lived :-).

  3. gvanrossum commented on Apr 12, 2019

    @gvanrossum
    Member
  4. ilevkivskyi commented on Apr 12, 2019

    @ilevkivskyi
    Member

    Superseded by python/typeshed#2911

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions