Python print isn't using __repr__, __unicode__ or __str__ for unicode subclass?

前端 未结 2 1800
面向向阳花
面向向阳花 2021-01-02 07:19

Python print isn\'t using __repr__, __unicode__ or __str__ for my unicode subclass when printing. Any clues as to what I am doing wron

2条回答
  •  爱一瞬间的悲伤
    2021-01-02 07:55

    The problem is that print doesn't respect __str__ on unicode subclasses.

    From PyFile_WriteObject, used by print:

    int
    PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
    {
    ...
            if ((flags & Py_PRINT_RAW) &&
        PyUnicode_Check(v) && enc != Py_None) {
        char *cenc = PyString_AS_STRING(enc);
        char *errors = fobj->f_errors == Py_None ? 
          "strict" : PyString_AS_STRING(fobj->f_errors);
        value = PyUnicode_AsEncodedString(v, cenc, errors);
        if (value == NULL)
            return -1;
    

    PyUnicode_Check(v) returns true if v's type is unicode or a subclass. This code therefore writes unicode objects directly, without consulting __str__.

    Note that subclassing str and overriding __str__ works as expected:

    >>> class mystr(str):
    ...     def __str__(self): return "str"
    ...     def __repr__(self): return "repr"
    ... 
    >>> print mystr()
    str
    

    as does calling str or unicode explicitly:

    >>> class myuni(unicode):
    ...     def __str__(self): return "str"
    ...     def __repr__(self): return "repr"
    ...     def __unicode__(self): return "unicode"
    ... 
    >>> print myuni()
    
    >>> str(myuni())
    'str'
    >>> unicode(myuni())
    u'unicode'
    

    I believe this could be construed as a bug in Python as currently implemented.

提交回复
热议问题