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:

  1. from typing import Text
  2.  
  3. def unicode_only(s: Text) -> Text:
  4. 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:

  1. from typing import AnyStr
  2.  
  3. def concat(x: AnyStr, y: AnyStr) -> AnyStr:
  4. return x + y
  5.  
  6. concat('a', 'b') # Okay
  7. concat(b'a', b'b') # Okay
  8. 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.