Skip to content

Format attribute name with repr() when formatting AttributeError error message #154610

Open

Description

@vstinner

Feature or enhancement

Some code paths format the attribute name with str() to format the AttributeError error message. Example:

>>> getattr(object(), "a'b")
AttributeError: 'object' object has no attribute 'a'b'

The quote character ' should be escaped in the error message ('a\'b'), or the attribute name should be quoted with " character ("a'b").

The expected error is:

AttributeError: 'object' object has no attribute "a'b"

I propose replacing str() with repr() to format the attribute name.

This issue is a follow-up of #153786 (comment) discussion (another AttributeError change).

Linked PRs

Activity

  1. added
    type-featureA feature request or enhancement
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    stdlibStandard Library Python modules in the Lib/ directory
    on Jul 24, 2026
  2. added a commit that references this issue on Jul 24, 2026
  3. serhiy-storchaka commented on Jul 24, 2026

    @serhiy-storchaka
    Member

    How does it work with StrEnum?

  4. vstinner commented on Jul 24, 2026

    @vstinner
    MemberAuthor

    How does it work with StrEnum?

    My PR changes how StrEnum instances and str subclasses are formatted.

    Currently, PyErr_Format(PyExc_AttributeError, "...%U", ..., name) calls PyUnicode_FromFormatV() which calls _PyUnicodeWriter_WriteStr() to render %U. The _PyUnicodeWriter_WriteStr(writer, obj) call expects a str instance and writes str.__str__(obj) even if the __str__() method is overridden in a str subclass.


    StrEnum example:

    import enum
    
    class Build(enum.StrEnum):
        DEBUG = enum.auto()
        OPTIMIZED = enum.auto()
    
    getattr(object(), Build.DEBUG)

    Before (Python 3.15):

    AttributeError: 'object' object has no attribute 'debug'
    

    After:

    AttributeError: 'object' object has no attribute <Build.DEBUG: 'debug'>
    

    Example of a str subclass:

    class MyStr(str):
        def __repr__(self):
            return '<custom repr>'
    
    getattr(object(), MyStr('abc'))

    Before (Python 3.15):

    AttributeError: 'object' object has no attribute 'abc'
    

    After:

    AttributeError: 'object' object has no attribute <custom repr>
    
  5. serhiy-storchaka commented on Jul 24, 2026

    @serhiy-storchaka
    Member

    __str__() should not be called for %U. We have %S for this.

  6. serhiy-storchaka commented on Jul 24, 2026

    @serhiy-storchaka
    Member

    My concerns:

    • Such errors are often used in EAFP code. Error message is generated, but not used. The faster it executes and the less third-party code that can fail is executed, the better.
    • Such errors can happen in stressful cases, for example in process of the interpreter shutdown or when it is failing from memory starvation. The less third-party code that can fail is executed, the better.

    %U rarely fails (especially if we forbid execution of __str__()). %R is more complex, it usually involves several memory allocations.

  7. vstinner commented on Jul 24, 2026

    @vstinner
    MemberAuthor

    Sometimes, I wish that we could more easily extend PyUnicode_FromFormat() formats. For example, it would be nice to have a format similar to %U but which would quote the string: similar to repr(str) but don't call __repr__() method on str subclasses. Adding a suffix such as %Uq format is not possible, since currently, it's parsed as %U format + q literal string. There is %#U where # usually means "alternative format". But I'm not sure if # relationship to "repr/quote" is obvious enough.

    Note: PEP 737 added %T, %#T, %N and %#N where # only changes the separator: use colon (:) instead of dot (.).

  8. serhiy-storchaka commented on Jul 25, 2026

    @serhiy-storchaka
    Member

    I thought about adding variants of %c and %s which escape non-printable characters.

  9. serhiy-storchaka commented on Jul 25, 2026

    @serhiy-storchaka
    Member

    Implemented in #154669.

  10. vstinner commented on Sep 17, 2026

    @vstinner
    MemberAuthor

    I created PR gh-157685 to add !R to f-string and add %#R to PyUnicode_FromFormat().

    I also created https://discuss.python.org/t/add-r-conversion-to-f-string-and-str-format-to-format-error-messages/109098 discussion. Changing string formatting concerns a lot of people, so I prefer to involve a larger audience.

  11. added a commit that references this issue on Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions