Similar to smart_str(), except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects.
(s, encoding="utf-8", strings_only=False, errors="strict")
| 51 | |
| 52 | |
| 53 | def force_str(s, encoding="utf-8", strings_only=False, errors="strict"): |
| 54 | """ |
| 55 | Similar to smart_str(), except that lazy instances are resolved to |
| 56 | strings, rather than kept as lazy objects. |
| 57 | |
| 58 | If strings_only is True, don't convert (some) non-string-like objects. |
| 59 | """ |
| 60 | # Handle the common case first for performance reasons. |
| 61 | if issubclass(type(s), str): |
| 62 | return s |
| 63 | if strings_only and is_protected_type(s): |
| 64 | return s |
| 65 | try: |
| 66 | if isinstance(s, bytes): |
| 67 | s = str(s, encoding, errors) |
| 68 | else: |
| 69 | s = str(s) |
| 70 | except UnicodeDecodeError as e: |
| 71 | raise DjangoUnicodeDecodeError(*e.args) from None |
| 72 | return s |
| 73 | |
| 74 | |
| 75 | def smart_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): |