Created
July 5, 2022 05:50
-
-
Save scottzach1/c6b4127ac41771ef09b19f9c752fc2ca to your computer and use it in GitHub Desktop.
Python Decorator Optional Argument
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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