Dynamic function with local variables in Python Programming Language?

Asked By: Lekha Dixit

Available Answers: 1

Answer #1#
Bhopal, India

For this simplified example, I think that what you have works pretty well (aside from being a bit hacky). While the i=i part can be ugly and tricky, it is a relatively well known way to make closures. Add a comment if you're afraid someone won't get it.

However, if you're doing something that's more complex, I'd definitely agree with S. Lott above.

One other possible approach:

def make_property(i, dict):"    def fget(self):"        return i""    dict['f%d' % i] = property(fget)""class Test(object):"    def __metaclass__(name, bases, dict):"        for i in range(5):"            make_property(i, dict)""        return type(name, bases, dict)

Personally, I feel that this makes the whole thing a lot easier to understand as you're separating out each iteration of the loop into its own function.

Comment Below


Would you like to join Ask Sawal!


  1. Ask Sawal is a fast growing question and answer discussion forum.

  2. 25 lakh+ questions were answered by our Ask Sawal Members.

  3. Each day 1000s of questions asked & 1000s of questions answered.

  4. Ask any question and get answer from 5 Lakh+ Ask Sawal Members.

  5. Constant moderation and reporting option makes questions and answers spam free.

  6. And also, we have free blogging platform. Write an article on any topic.

  7. We have 10000+ visitors each day. So a beneficial platform for link building.

  8. We are allowing link sharing. Create backlinks to your blog site or any site.

  9. Gain extra passive income by sharing your affiliate links in articles and answers.