Skip to content

Instantly share code, notes, and snippets.

@scottzach1
Created July 5, 2022 05:50
Show Gist options
  • Save scottzach1/c6b4127ac41771ef09b19f9c752fc2ca to your computer and use it in GitHub Desktop.
Save scottzach1/c6b4127ac41771ef09b19f9c752fc2ca to your computer and use it in GitHub Desktop.
Python Decorator Optional Argument
#!/bin/python3
import functools
from typing import Callable
def wrapped(fn: Callable[..., str] = None, /, chars: str = '"') -> Callable[..., str] or str:
"""
A decorator to wrap a method response in quotes
:param fn: (pos only) function to decorate
:param chars: the characters to surround before and after fn() response
:return: fn() response wrapped in chars
"""
def wrapped_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return f"{chars}{func(*args, **kwargs)}{chars}"
return wrapper
if fn:
return wrapped_decorator(fn)
return wrapped_decorator
@wrapped
def string() -> str:
return 'ABC'
assert string() == '"ABC"'
@wrapped(chars='_')
def string() -> str:
return 'ABC'
assert string() == '_ABC_'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment