Skip to content

BytesIO.name and StringIO.name should not be defined #1790

Closed

Description

@srittau

Please consider the following Python 3.6 code:

from io import BytesIO


class NamedBytesIO(BytesIO):

    def __init__(self, content: bytes, name: str) -> None:
        super().__init__(content)
        self.name = name

mypy 0.560 complains:

test.py:8: error: Property "name" defined in "NamedBytesIO" is read-only

This is due to the fact that in typeshed BytesIO derives from BinaryIO, which defines the name property. The actual BytesIO implementation does not have such an attribute:

>>> from io import BytesIO
>>> BytesIO(b"").name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_io.BytesIO' object has no attribute 'name'

Interestingly, StringIO does not have this problem:

from io import StringIO


class NamedStringIO(StringIO):

    def __init__(self, content: str, name: str) -> None:
        super().__init__(content)
        self.name = name

This checks fine with mypy, since the StringIO stub includes a name field, which also does not match the implementation:

>>> from io import StringIO
>>> StringIO("").name
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_io.StringIO' object has no attribute 'name'

Activity

  1. gvanrossum commented on Dec 17, 2017

    @gvanrossum
    Member

    Ow, this cuts deep. It seems class IO defined in types.py has a name property. This is one of the problems with poorly specified protocols like IO -- we guess at what's part of the spec and what isn't. We'll probably need another helper class to represent the kinds of files returned by open(), and tighten up the spec of types.IO.

  2. srittau commented on Dec 21, 2017

    @srittau
    CollaboratorAuthor

    A previous issue that discussed StringIO.name: #598.

  3. gvanrossum commented on Dec 31, 2017

    @gvanrossum
    Member

    Rather than trying to fix the deep issues (which seem impossibly hard) let's just add

    name = ...  # type: str

    to BytesIO so it matches the hack we have for StringIO.

  4. gvanrossum commented on Dec 31, 2017

    @gvanrossum
    Member

    (Can you make a PR?)

  5. added a commit that references this issue on Jan 2, 2018
    717fb35
  6. added a commit that references this issue on Jan 26, 2018
    6d7173b
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