When writing a function in Python with type hints like this: It translates to this type hint: Optional[Token]. With optional, a None value is accepted too. When writing the same type hint for a class field, it doesn’t behave the same: Here type hint checkers like the integrated one in PyCharm reports: Expected type ‘Token’, got None instead. My questions
Tag: typechecking
Subclassing Sequence with proper type hints in Python
I’m trying to implement a kind of custom sequence class in Python: Now I want to check that mypy is aware that elements of MySequence are items of type T: So it fails: mypy knows nothing about items of foo. The same example for ordinary Sequence works: If I’m trying to add type annotations to __getitem__ implementation, I have another
Use isinstance to test for Unicode string
How can I do something like: But I would like isinstance to return True for this Unicode encoded string. Is there a Unicode string object type? Answer Test for str: or, if you must handle bytestrings, test for bytes separately: The two types are deliberately not exchangible; use explicit encoding (for str -> bytes) and decoding (bytes -> str) to