Created
May 14, 2024 06:12
-
-
Save stephenmwilkins/ff9e9d2293e0cf109a60d531d2572fb2 to your computer and use it in GitHub Desktop.
Python decorator enabling use of British English named arguments
This file contains hidden or 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
def enable_british_english(func): | |
""" | |
A simple decorator allowing users to provide British english | |
arguments to functions and methods. | |
Example: | |
@enable_british_english | |
def favourite(color=None): | |
print(f"my favourite colour is {color}") | |
favourite(color="red") | |
> my favourite colour is red | |
favourite(colour="blue") | |
> my favourite colour is blue | |
""" | |
def wrapper(**kwargs): | |
""" | |
Arguments: | |
kwargs | |
List of kwargs originally passed to decorated function. | |
""" | |
# dictionary (obviously needs exapanding) | |
british_to_american = { | |
'colour': 'color', | |
'colours': 'colors', | |
'centre': 'center', | |
'catalogue': 'catalog' | |
} | |
# list of new kwargs to pass to function | |
kwargs_ = {} | |
for k, v in kwargs.items(): | |
if k in british_to_american.keys(): | |
kwargs_[british_to_american[k]] = v | |
else: | |
kwargs_[k] = v | |
return func(**kwargs_) | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment