Text and AnyStr
Sometimes you may want to write a function which will accept only unicodestrings. This can be challenging to do in a codebase intended to run inboth Python 2 and Python 3 since str
means something different in bothversions and unicode
is not a keyword in Python 3.
To help solve this issue, use Text
which is aliased tounicode
in Python 2 and to str
in Python 3. This allows you toindicate that a function should accept only unicode strings in across-compatible way:
- from typing import Text
- def unicode_only(s: Text) -> Text:
- return s + u'\u2713'
In other cases, you may want to write a function that will work with anykind of string but will not let you mix two different string types. To doso use AnyStr
:
- from typing import AnyStr
- def concat(x: AnyStr, y: AnyStr) -> AnyStr:
- return x + y
- concat('a', 'b') # Okay
- concat(b'a', b'b') # Okay
- concat('a', b'b') # Error: cannot mix bytes and unicode
For more details, see Type variables with value restriction.
Note
How bytes
, str
, and unicode
are handled between Python 2 andPython 3 may change in future versions of mypy.