Escapism
Escapism is a Python library providing a simple, generic API for escaping strings. It offers functions for reversible escaping, ideal for preserving string content across systems, and a 'safe_slug' API for creating unique, URL-safe or filesystem-safe strings which are not necessarily reversible. The current version is 1.1.0, and it is part of the Project Jupyter ecosystem, with development continuing as needed.
Warnings
- breaking The `safe_slug` function (added in version 1.1) is inherently lossy and not designed for round-trip conversion. It prioritizes creating valid and unique identifiers for contexts like filenames or URLs by transforming/hashing input strings, which means the original string cannot be recovered.
- gotcha If you use a non-default `escape_char` when calling `escapism.escape()`, you *must* provide the same `escape_char` to `escapism.unescape()` to correctly reverse the operation. Failing to do so will result in an incorrect or incomplete unescaping.
- gotcha The default set of 'safe' characters for `escapism.escape()` includes ASCII letters and numbers. Other characters will be escaped. For `escapism.safe_slug()`, the default `is_valid` callable applies strict Kubernetes-like rules, requiring lowercase ASCII letters, numbers, and hyphens, starting with a letter and ending with a letter or number, and a length between 1 and 63.
Install
-
pip install escapism
Imports
- escape
from escapism import escape
- unescape
from escapism import unescape
- safe_slug
from escapism import safe_slug
Quickstart
import escapism
import string
# Reversible escaping
escaped = escapism.escape('my string with spaces and /slashes!', escape_char='_')
print(f"Escaped: {escaped}") # Output: my_20string_20with_20spaces_20and_2Fslashes!
original = escapism.unescape(escaped, escape_char='_')
print(f"Unescaped: {original}") # Output: my string with spaces and /slashes!
# Escaping with custom safe characters and escape character
safe_chars = string.ascii_letters + string.digits + '@_-.+'
custom_escaped = escapism.escape('foø-bar@%!xX?', safe=safe_chars, escape_char=r'%')
print(f"Custom Escaped: {custom_escaped}") # Output: fo%C3%B8-bar@%25%21xX%3F
custom_original = escapism.unescape(custom_escaped, escape_char=r'%')
print(f"Custom Unescaped: {custom_original}") # Output: foø-bar@%!xX?
# Lossy slug generation for unique, safe names (e.g., for Kubernetes)
# safe_slug ensures validity and uniqueness (by hashing if needed)
slug_name = escapism.safe_slug('My User Name With Special Chars & A Long Name That Needs To Be Shortened And Unique')
print(f"Safe Slug: {slug_name}")
already_safe_slug = escapism.safe_slug('simple-name-123')
print(f"Already Safe Slug: {already_safe_slug}") # Output: simple-name-123