Opened 3 years ago

Closed 3 years ago

#33525 closed Cleanup/optimization (wontfix)

decorator @html_safe removes completely old class.__str__ method.

Reported by: Maxim Danilov Owned by: nobody
Component: Utilities Version: 4.0
Severity: Normal Keywords: html_string, SafeString
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

I can not to get normal str method from safe_string.

Fro example:

@html_safe
class TranslatableText(str):
    """Class like a string but returns values depends on get_language."""

After that str(TranslatableText) is always SafeString. If i want call old str method it is not possible: html_safe destroy it in django\utils\html.py, rows 376-378

    klass_str = klass.__str__
    klass.__str__ = lambda self: mark_safe(klass_str(self))
    klass.__html__ = lambda self: str(self)
    return klass

But it is easy to repair:

    klass._old_str_method = klass.__str__
    klass.__str__ = lambda self: mark_safe(klass._old_str_method(self))
    klass.__html__ = lambda self: str(self)
    return klass

After that, not only can i get SafeString object, it is also possible to call klass._old_str_method and get BaseString object

Change History (1)

comment:1 by Mariusz Felisiak, 3 years ago

Resolution: wontfix
Status: newclosed

Thanks for this ticket, however accessing and old __str__() method after @html_safe sounds really niche. You can always create your own decorator for this.

Note: See TracTickets for help on using tickets.
Back to Top