Created
February 7, 2024 13:11
-
-
Save costastf/41a740a939ea98d98ac5202ac86b8635 to your computer and use it in GitHub Desktop.
Naming decorator
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
from functools import wraps | |
class InvalidCase(Exception): | |
"""The case chose is not valid.""" | |
VALID_CASES = ['title', 'lower', 'upper'] | |
def apply_convention(function_argument=None, *, case='title', separator='-'): | |
if case not in VALID_CASES: | |
raise InvalidCase(f'Case {case} is not valid, please choose one of {VALID_CASES}.') | |
def decorate(function): | |
@wraps(function) | |
def wrap(*args, **kwargs): | |
items = function(*args, **kwargs) | |
return separator.join([getattr(item, case)() for item in items]) | |
return wrap | |
if function_argument: | |
return decorate(function_argument) | |
return decorate | |
@apply_convention | |
def name(): | |
return ['tes', 'bla', 'sdf'] | |
@apply_convention(separator='.') | |
def name2(): | |
return ['tes', 'bla', 'sdf'] | |
@apply_convention(case='lower') | |
def name3(): | |
return ['tes', 'bla', 'sdf'] | |
@apply_convention(case='upper', separator='/') | |
def name4(): | |
return ['tes', 'bla', 'sdf'] | |
if __name__ == '__main__': | |
print(name()) | |
print(name2()) | |
print(name3()) | |
print(name4()) | |
# ❯ python naming.py | |
# Tes-Bla-Sdf | |
# Tes.Bla.Sdf | |
# tes-bla-sdf | |
# TES/BLA/SDF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment