python : understaning partial functions -
i trying head around snippet :
def a_func(a, b, c): print "a: %s\nb: %s\nc: %s" %(a, b, c) def partial(fn, *args): print "args in partial : %s" %str(args) def fn_part(*fn_args): print "fn_args in fn_part : %s" %fn_args return fn(*args+fn_args) return fn_part print_fn = partial(a_func, 'a', 'b') print_fn('c')
the output :
args in partial : ('a', 'b') fn_args in fn_part : c a: b: b c: c
how control flow here ?
the function object print_fn
points fn_part
, has variables predefined (a
, b
). how can view variables defined function ?
the fn_part()
function accesses args
closure. read returned function object:
>>> print_fn = partial(a_func, 'a', 'b') args in partial : ('a', 'b') >>> print_fn.__closure__ (<cell @ 0x102a90be8: tuple object @ 0x10075bf38>, <cell @ 0x102a901d8: function object @ 0x102aa1848>) >>> print_fn.__closure__[0].cell_contents ('a', 'b')
you cannot alter closure; you'd create new partial()
object instead, or call original function directly.
Comments
Post a Comment