Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8526579
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T08:18:42+00:00 2026-06-11T08:18:42+00:00

Okay, bear with me on this, I know it’s going to look horribly convoluted,

  • 0

Okay, bear with me on this, I know it’s going to look horribly convoluted, but please help me understand what’s happening.

from functools import partial

class Cage(object):
    def __init__(self, animal):
        self.animal = animal

def gotimes(do_the_petting):
    do_the_petting()

def get_petters():
    for animal in ['cow', 'dog', 'cat']:
        cage = Cage(animal)

        def pet_function():
            print "Mary pets the " + cage.animal + "."

        yield (animal, partial(gotimes, pet_function))

funs = list(get_petters())

for name, f in funs:
    print name + ":", 
    f()

Gives:

cow: Mary pets the cat.
dog: Mary pets the cat.
cat: Mary pets the cat.

So basically, why am I not getting three different animals? Isn’t the cage ‘packaged’ into the local scope of the nested function? If not, how does a call to the nested function look up the local variables?

I know that running into these kind of problems usually means one is ‘doing it wrong’, but I’d like to understand what happens.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T08:18:44+00:00Added an answer on June 11, 2026 at 8:18 am

    The nested function looks up variables from the parent scope when executed, not when defined.

    The function body is compiled, and the ‘free’ variables (not defined in the function itself by assignment), are verified, then bound as closure cells to the function, with the code using an index to reference each cell. pet_function thus has one free variable (cage) which is then referenced via a closure cell, index 0. The closure itself points to the local variable cage in the get_petters function.

    When you actually call the function, that closure is then used to look at the value of cage in the surrounding scope at the time you call the function. Here lies the problem. By the time you call your functions, the get_petters function is already done computing it’s results. The cage local variable at some point during that execution was assigned each of the 'cow', 'dog', and 'cat' strings, but at the end of the function, cage contains that last value 'cat'. Thus, when you call each of the dynamically returned functions, you get the value 'cat' printed.

    The work-around is to not rely on closures. You can use a partial function instead, create a new function scope, or bind the variable as a default value for a keyword parameter.

    • Partial function example, using functools.partial():

      from functools import partial
      
      def pet_function(cage=None):
          print "Mary pets the " + cage.animal + "."
      
      yield (animal, partial(gotimes, partial(pet_function, cage=cage)))
      
    • Creating a new scope example:

      def scoped_cage(cage=None):
          def pet_function():
              print "Mary pets the " + cage.animal + "."
          return pet_function
      
      yield (animal, partial(gotimes, scoped_cage(cage)))
      
    • Binding the variable as a default value for a keyword parameter:

      def pet_function(cage=cage):
          print "Mary pets the " + cage.animal + "."
      
      yield (animal, partial(gotimes, pet_function))
      

    There is no need to define the scoped_cage function in the loop, compilation only takes place once, not on each iteration of the loop.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Okay this is going to seem really dumb but bear with me please. A
Okay, this might seem like a weird question, but bear with me. So I
Okay, this is a bit complicated so please bear with me. :) We have
Okay, I'm very new to Java so please bear with me. I am using
Okay, I feel a bit foolish for having to ask this but I guess
Okay, so this is a long long shot but here it goes... When IE
OKay, this is probably pretty noob, but I couldn't find how to solve it.
Okay, so I've known about this for like 600 years now, but I've only
Okay So I know this is super basic and I should know how to
Okay so I need help understanding something. I understand how ? : are used

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.