We can modify and/or add other parameters like here where I modify the url
parameter for some_requests_dot_get_function
via some_decorator
:
url = 'google.com'#'https://www.google.com/'
def some_decorator(some_function):
def wrapper(*args, url, **kwargs):
some_function.url = 'https://www.' + url + '/'
return some_function(*args, url=some_function.url, **kwargs)
return wrapper
@some_decorator
def some_requests_dot_get_function(*args, url, **kwargs):
return requests.get(*args, url=url, **kwargs).content.decode('utf-8')
some_requests_dot_get_function(url=url)
Not sure the exact use case you're intending, but maybe it could justify using some dict
annotations
for different functions to modify parameters depending on its particular item
(s), that way at least you only have to modify this decorator rather than every function it decorates:
url = 'google.com'#'https://www.google.com/'
def some_decorator(some_function):
def wrapper(*args, url, **kwargs):
if some_function.__annotations__['return'].__getitem__('some_annotation') > 0:
some_function.url = 'https://www.' + url + '/'
else:
some_function.url = url
return some_function(*args, url=some_function.url, **kwargs)
return wrapper
@some_decorator
def some_requests_dot_get_function(*args, url, **kwargs) -> {'some_annotation': 2}:
return requests.get(*args, url=url, **kwargs).content.decode('utf-8')
some_requests_dot_get_function(url=url)
... or we could rely on the names of the functions to set the parameters in some_decorator
:
url = 'google.com'#'https://www.google.com/'
def some_decorator(some_function):
def wrapper(*args, url, **kwargs):
if some_function.__name__.__contains__('some_requests'):
some_function.url = 'https://www.' + url + '/'
elif some_function.__name__.__contains__('some_other_requests'):
some_function.url = 'https://www.' + url + '/?client=safari'
else:
some_function.url = url
return some_function(*args, url=some_function.url, **kwargs)
return wrapper
@some_decorator
def some_requests_dot_get_function(*args, url, **kwargs):
return 'some: ' + requests.get(*args, url=url, **kwargs).content.decode('utf-8')
@some_decorator
def some_other_requests_dot_get_function(*args, url, **kwargs):
return 'some other: ' + requests.get(*args, url=url, **kwargs).content.decode('utf-8')
some_requests_dot_get_function(url=url)
some_other_requests_dot_get_function(url=url)