What is the correct docstring for unicode/str parameter in Python 2 and 3

Viewed 223

I have a method that accepts a unicode parameter in Python 2, but in Python 3 it accepts a str.
I am wondering how I should write the sphinx docstring for this function:
:param unicode text: or :param str text: or a seperate documentation for Python 2 and Python 3?

Example:

def myfunction(text):
    """Do something with text
    :param unicode text: Must be unicode
    :rtype: unicode
    :raises TypeError: If text is not a unicode
    """
    if PY2 and not isinstance(text, unicode):
        raise TypeError("Argument 'text' must be unicode")
    ...
    return text
1 Answers

I don't believe that there's any easier way that six.text_type.

But couple of thing on top of that: - please double-check if you actually need unicode and not basestring, this looks non-pythonic - if you're in the middle of migration to PY3 and this is compatibility thing — just go with str and document for PY3 - write type for PY3 and clarify difference in description. Docstrings is 100% for humans, just think if its easier to read 1 note in rare case or decypher weird compatibility type every time

Related