Skip to content

Instantly share code, notes, and snippets.

@edouardp
Created July 18, 2015 20:13
Show Gist options
  • Save edouardp/9c4f4697775c657b5858 to your computer and use it in GitHub Desktop.
Save edouardp/9c4f4697775c657b5858 to your computer and use it in GitHub Desktop.
Python decorator that ignores unneeded keyword arguments
import inspect
def ignore_unused_args(f):
arg_spec = inspect.getargspec(f)
def new_f(*args, **kwargs):
new_kwargs = {key:kwargs[key] for key in arg_spec.args if key in kwargs}
return f(*args, **new_kwargs)
new_f.spec = arg_spec
return new_f
# Example Usage
@ignore_unused_args
def fn_1(a, b, c=100):
print a,b,c
fn_1(a=1, b=2, c=3, d=4)
# Prints "1 2 3"
# Without the decorator, it would give an error:
# TypeError: fn_1() got an unexpected keyword argument 'd'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment