Home Python variable scope in dynamic functions
Reply: 0

Python variable scope in dynamic functions

user7459
1#
user7459 Published in September 20, 2018, 10:22 pm

This question already has an answer here:

  • Creating functions in a loop 1 answer

I recently implemented a function factory that didn't scope a variable the way I expected.

I found a solution, but I don't know why it works.

So although I don't strictly need a solution to this problem, I've posted this question in the hope of learning something about variable scope.

Problematic Code

# Create function list
func_list = []
for i in [1, 2]:
    def _func():
        print("%i" % i)
    func_list.append(_func)

# Execute
for f in func_list:
    f()

Gives the same ouptut; always the last loop element:

2
2

Solution

# Create function list
def make_func(i):
    def _func():
        print("%i" % i)

    return _func

func_list = []
for i in [1, 2]:
    func_list.append(make_func(i))

# Execute
for f in func_list:
    f()

Gives what I expected all along:

1
2

Why? so my questions are:

  • Why doesn't the first method work?
  • How is the working implementation functionally different to the first?
share|improve this question

marked as duplicate by schwobaseggl python StackExchange.ready(function() { if (StackExchange.options.isMobile) return; $('.dupe-hammer-message-hover:not(.hover-bound)').each(function() { var $hover = $(this).addClass('hover-bound'), $msg = $hover.siblings('.dupe-hammer-message'); $hover.hover( function() { $hover.showInfoMessage('', { messageElement: $msg.clone().show(), transient: false, position: { my: 'bottom left', at: 'top center', offsetTop: -7 }, dismissable: false, relativeToBody: true }); }, function() { StackExchange.helpers.removeMessages(); } ); }); }); Feb 13 at 10:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • I guess return function returns the value of it rather than the reference. Hence the second code works out. Though I am not entirely sure. – kawadhiya21 Feb 13 at 10:53

1 Answer 1

active oldest votes
up vote 0 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.324035 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO