Skip to content

mypy returns invalid type: "bytes" in classes that define a bytes instance attribute #3687

@adewes

Description

@adewes

When trying to add type annotations to a project (https://github.com/DCSO/flor), mypy would complain that bytes was not a valid type, which was quite puzzling to say the least. After some head scratching and searching in the issue log I was able to reproduce the problem with a simple module (Python 3.5.2+ with mypy 0.511):

class Foo(object):

    def __init__(self) -> None:
        self.bytes = bytearray(b"foo")

    def bar(self, f : bytes):
        return f + b"test"

foo = Foo()

foo.bar(b"test")

Running mypy example.py returns the following error messages:

example.py:6: error: Invalid type "bytes"
example.py:7: error: Unsupported left operand type for + (object)

When renaming self.bytes to self._bytes, no issues are reported. It seems that mypy mistakes self.bytes for a class variable, although it is an instance variable and not visible at the declaration time of function bar.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions