python - Dynamically adding key-arguments to method -
i set default key-arguments of instance method dynamically. example, with
class module(object): def __init__(self, **kargs): set-default-key-args-of-method(self.run, kargs) # change run arguments def run(self, **kargs): print kargs
we have:
m = module(ans=42) m.run.im_func.func_code.co_argcount # => 2 m.run.im_func.func_code.co_varnames # => ('self','ans','kargs') m.run.im_func.func_defaults # => (42,) m.run() # print {'ans':42}
i tried types.codetype (which don't understand) function (not method) , got work (well not-to-fail), added key-arguments did not show in kargs dictionary of function (it print {})
the change has done current instance only. actually, using class right (i'm oo in mind) class method, function maybe better. like:
def wrapped_run(**kargs): def run(**key_args): print key_args return wrap-the-run-function(run, kargs) run = wrapped_run(ans=42) run.func_code.co_argcount # => 1 run.func_code.co_varnames # => ('ans','key_args') ## keep 'key_args' or not run.func_defaults # => (42,) run() # print {'ans':42}
any advise or idea welcome.
a little on context:
the module class kind function wrapper, can use include lower-end function in dataflow system automatically add intermediate procedures. module run function (actually, it's __call___ function) have correct api in order dataflow system nicely generate correct module's input transparently.
i'm using python 2.7
kwargs
dictionary, , should need save later. user can override values.
class module(object): def __init__(self, **kwargs): self.defaults = kwargs def run(**kwargs): values = dict(self.defaults.items() + kwargs.items()) print values
edit
are perhaps looking lambda
function generation?
def wrapfunc(**kwargs): def run(kwargs): print kwargs return lambda x: run(dict(kwargs.items() + x.items())) run = wrapfunc(ans=42) run({}) run({'ans':12})
Comments
Post a Comment