Created
July 17, 2019 02:19
-
-
Save FGtatsuro/7d84425759ca3eb08a366d6dc76d1886 to your computer and use it in GitHub Desktop.
Dynamic injected value
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
import functools | |
import random | |
import typing | |
def decorator( | |
field_name: str = 'injected_field' | |
): | |
def inner(func: typing.Callable): | |
@functools.wraps(func) | |
def _inner( | |
required1, | |
required2, | |
*args, | |
**kwargs | |
): | |
if field_name not in kwargs: | |
# Actually, we can generate default value by other ways. | |
# ex. Call other functions, and use its return value. | |
kwargs[field_name] = random.randint(1, 100) | |
return func( | |
required1, | |
required2, | |
*args, | |
**kwargs | |
) | |
return _inner | |
return inner | |
@decorator() | |
def func1( | |
required1, | |
required2, | |
*, | |
injected_field = None | |
): | |
print(injected_field) | |
func1(1, 2, injected_field=5) | |
func1(1, 2, injected_field=6) | |
func1(1, 2) | |
func1(1, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment