Search code examples
pythondecoratorkeyword-argument

How to filter the **kwargs before passing them to a function?


I have a decorator:

def decorator(func):
     @wraps(func)
     def wrapper(*args, **kwargs):
         print('something', **kwargs)

         # kwargs.pop('task_id', None)

         func(*args, **kwargs)
        
         print('something', **kwargs)
    
     return wrapper 

I need to filter the kwargs in such a way that they can be passed to the calling function without the task_id, but not removed. Since after I will need to fully use kwargs. Does anyone know how can this be done?


Solution

  • You can add task_id as a separate keyword argument, so it will be automatically excluded from other kwargs:

    def decorator(func):
         @wraps(func)
         def wrapper(*args, task_id=None, **kwargs):
             func(*args, **kwargs)
        
         return wrapper