You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
bytes(obj) rejected even when obj implements __bytes__ #3989
The problem is that SupportsBytes (and several other classes) is not yet defined as a protocol. This will be fixed by python/typeshed#1220, a temporary workaround is to explicitly inherit A from typing.SupportsBytes.
Unfortunately the workaround breaks using isinstance with the class:
#!/usr/bin/env python3importtypingclassA(typing.SupportsBytes):
def__bytes__(self) ->bytes:
returnb'An A'print(bytes(A()))
assertisinstance(None, A)
at runtime gives
b'An A'
Traceback (most recent call last):
File "./test.py", line 10, in <module>
assert isinstance(None, A)
File "/usr/lib/python3.5/typing.py", line 1269, in __instancecheck__
raise TypeError("Protocols cannot be used with isinstance().")
TypeError: Protocols cannot be used with isinstance().
I managed to work around it by replacing bytes(a) with bytes(cast(SupportsBytes, a)).
Concerning the isinstance() error, it looks like you are using an older version of typing, this is fixed in latest version. You could try updating Python (or upgrading to 3.6), but your workaround (using cast) is perfectly OK.
Activity
ilevkivskyi commentedon Sep 23, 2017
The problem is that
SupportsBytes(and several other classes) is not yet defined as a protocol. This will be fixed by python/typeshed#1220, a temporary workaround is to explicitly inheritAfromtyping.SupportsBytes.bmerry commentedon Sep 23, 2017
Unfortunately the workaround breaks using
isinstancewith the class:at runtime gives
I managed to work around it by replacing
bytes(a)withbytes(cast(SupportsBytes, a)).ilevkivskyi commentedon Sep 23, 2017
Concerning the
isinstance()error, it looks like you are using an older version oftyping, this is fixed in latest version. You could try updating Python (or upgrading to 3.6), but your workaround (usingcast) is perfectly OK.bmerry commentedon Mar 11, 2018
It works with the current version of mypy (0.570), so closing.