Unicode String Decorator: A Practical Guide for Python Developers

Build a Flexible Unicode String Decorator in 10 Minutes

What you’ll get (10-minute goal)

  • A clear, minimal Python decorator that wraps function string outputs with customizable Unicode decorations.
  • Examples for single-line and multi-line strings.
  • Quick notes on Unicode handling and Python versions.

Decorator concept

Create a decorator that intercepts a function’s return value (assumed to be a string) and adds a border, prefix/suffix, or other Unicode ornament. Make it configurable via parameters so you can reuse it for different styles.

Ready-to-use decorator (Python 3.8+)

python

from functools import wraps from typing import Callable def unicode_decorator(left: str = “╔”, right: str = “╗”, pad: str = ” “, top: str = “═”, bottom: str = “═”): ”“” Wraps a function’s string output with a simple box using Unicode characters. Usage: @unicode_decorator(left=‘╔’, right=‘╗’, pad=’ ‘) “”” def decorator(func: Callable): @wraps(func) def wrapper(*args, kwargs): result = func(*args, kwargs) if result is None: return result s = str(result) lines = s.splitlines() or [””] width = max(len(line) for line in lines) top_line = f”{left}{top (width + 2)}{right} bottom_line = f”{left.replace(‘╔’,‘╚’)}{bottom (width + 2)}{right.replace(‘╗’,‘╝’)} middle = ” “.join(f”{left}{pad}{line.ljust(width)}{pad}{right} for line in lines) return ” “.join([top_line, middle, bottomline]) return wrapper return decorator

Examples

python

@unicodedecorator(left=‘╔’, right=‘╗’, pad=’ ‘) def greet(name): return f”Hello, {name}!” print(greet(“Ava”))

Output:

Code

╔════════════╗ ╔ Hello, Ava! ╗ ╚════════════╝

Multi-line:

python

@unicode_decorator(left=‘┌’, right=‘┐’, pad=’ ‘) def poem(): return “Roses are red Violets are blue” print(poem())

Tips

  • Use len() for width which measures code units; for full Unicode-aware width (emoji, wide CJK), use wcwidth library to compute display width.
  • For non-string returns, either convert to str() or skip decorating.
  • Make decorative characters parameters or accept style presets (e.g., “double”, “single”, “rounded”).

Variations to try

  • Add alignment option: left/center/right.
  • Support color escape codes (be careful with width calc).
  • Create HTML-safe decorator that wraps content in spans with emoji.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *