Escapism

1.1.0 · active · verified Wed Apr 15

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

Install

Imports

Quickstart

This quickstart demonstrates the core functionalities: `escape` for reversible encoding/decoding, `unescape` to revert `escape` operations, and `safe_slug` for creating valid, unique, and often lossy identifiers suitable for system names like Kubernetes object names or filenames. It shows how to customize safe characters and escape characters for precise control.

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

view raw JSON →