Created
May 30, 2011 19:45
-
-
Save jedbrown/999371 to your computer and use it in GitHub Desktop.
Subset default arguments in Python
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
#!/usr/bin/env python | |
def withvars(f): | |
def wrapper(self,*args,**kwargs): | |
tmp = self.vars.copy() | |
tmp.update(kwargs) | |
return f(self,*args,**tmp) | |
return wrapper | |
def withvars_censor(f): | |
def wrapper(self,*args,**kwargs): | |
kwargs.update(self.vars) | |
return f(self,*args,**kwargs) | |
return wrapper | |
class Foo: | |
def __init__(self): | |
self.vars = dict(a=100,b=200,c=300,d=400,e=500) | |
@withvars | |
def f1(self,x,y,z,a,c,**unused): | |
print(x,y,z,a,c) | |
@withvars | |
def f2(self,x,c,e,**unused): | |
print(x,c,e) | |
@withvars_censor | |
def f2_censor(self,x,c,e,**unused): | |
print(x,c,e) | |
foo = Foo() | |
foo.f1(1,2,3) # 1 2 3 100 300 | |
foo.f1(z=-3,x=-1,y=-2) # -1 -2 -3 100 300 | |
foo.f2(9) # 9 300 500 | |
foo.f2(9,c=10) # 9 10 500 | |
foo.f2_censor(9,c=10) # 9 300 500 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment