Pass name to nested function in Python? -
what (if anything) different between using name in nested function , passing name nested function? if there's no difference, preferred convention?
def foo(bar): def put(): bar.append('world!') print(', '.join(bar)) put() foo(['hello']) versus
def foo(bar): def put(bar): bar += ['world!'] print(', '.join(bar)) put(bar) foo(['hello'])
the difference in first one, bar variable in scope of parent function, can used in child function , unless assignment on (this case similar using global variables in function) . example -
>>> def foo(bar): ... def put(): ... bar = bar + ['world'] ... print(', '.join(bar)) ... put() ... >>> >>> foo(['hello']) traceback (most recent call last): file "<stdin>", line 1, in <module> file "<stdin>", line 5, in foo file "<stdin>", line 3, in put unboundlocalerror: local variable 'bar' referenced before assignment in case if want use bar , assign well, need use nonlocal keyword , example -
>>> def foo(bar): ... def put(): ... nonlocal bar ... bar = bar + ['world!'] ... print(', '.join(bar)) ... put() ... >>> foo(['hello']) hello, world! whereas in second one, bar local variable put() function (because argument it) , can assigned without above unboundlocalerror , example -
>>> def foo(bar): ... def put(bar): ... bar = bar + ['world!'] ... print(', '.join(bar)) ... put(bar) ... >>> >>> foo(['hello']) hello, world! i prefer explicitly passing required arguments done in second case.
Comments
Post a Comment