fork download
  1. import inspect
  2. from types import FunctionType
  3.  
  4. def ensure_kwargs(func):
  5. if func.__code__.co_flags & inspect.CO_VARKEYWORDS:
  6. return func
  7. return FunctionType(
  8. code=func.__code__.replace(
  9. co_flags=func.__code__.co_flags | inspect.CO_VARKEYWORDS,
  10. co_varnames=func.__code__.co_varnames + ('kwargs',),
  11. co_nlocals=func.__code__.co_nlocals + 1
  12. ),
  13. globals=func.__globals__,
  14. name=func.__name__,
  15. argdefs=func.__defaults__,
  16. closure=func.__closure__
  17. )
  18.  
  19. def test1(x, z=1, **kwargs):
  20. print(f'{x=}, {z=}, {kwargs=}')
  21. def test2(x, y=1):
  22. print(f'{x=}, {y=}')
  23. def test3(x, y=1, z=1):
  24. print(f'{x=}, {y=}, {z=}')
  25.  
  26. def call_center(**kwargs):
  27. for test in tests:
  28. test(**kwargs)
  29. tests = list(map(ensure_kwargs, [test1, test2, test3]))
  30. call_center(x=1, y=2)
  31. call_center(x=3, z=4)
Success #stdin #stdout 0.25s 18424KB
stdin
Standard input is empty
stdout
x=1, z=1, kwargs={'y': 2}
x=1, y=2
x=1, y=2, z=1
x=3, z=4, kwargs={}
x=3, y=1
x=3, y=1, z=4