Is this a closure?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ssecorp

    Is this a closure?

    A method on a class:

    def printSelf(self) :
    def printReviews():
    for review in self.reviews:
    review.printSel f()
    print "Idnbr: ", self.idnumber, "Reviews: ", printReviews()

    I don't have to pass an argument to printReviews because everything
    defined inside printSelf is aware of outer variables? Or is that
    wrong? If it is right, is this what a closure means?

    Because Python is lexically scoped right? Is lexical scope+closures =
    organized dynamic scope kind of if you get my point?

  • Chris Rebert

    #2
    Re: Is this a closure?

    Yes, printReviews() is a closure. In particular, it's closing over the
    variable "self", which it's getting lexically from printSelf().
    - Chris

    On Sun, Aug 31, 2008 at 4:53 PM, ssecorp <circularfunc@g mail.comwrote:
    A method on a class:
    >
    def printSelf(self) :
    def printReviews():
    for review in self.reviews:
    review.printSel f()
    print "Idnbr: ", self.idnumber, "Reviews: ", printReviews()
    >
    I don't have to pass an argument to printReviews because everything
    defined inside printSelf is aware of outer variables? Or is that
    wrong? If it is right, is this what a closure means?
    >
    Because Python is lexically scoped right? Is lexical scope+closures =
    organized dynamic scope kind of if you get my point?
    >
    --

    >

    --
    Follow the path of the Iguana...

    Comment

    • John Machin

      #3
      Re: Is this a closure?

      On Sep 1, 9:53 am, ssecorp <circularf...@g mail.comwrote:
      A method on a class:
      >
      def printSelf(self) :
      def printReviews():
      for review in self.reviews:
      review.printSel f()
      print "Idnbr: ", self.idnumber, "Reviews: ", printReviews()
      >
      The above appears to be more or less identical in effect to:
      def printSelf(self) :
      print "Idnbr: ", self.idnumber, "Reviews: "
      for review in self.reviews:
      review.printSel f()
      except for spacing and more importantly the second version won't print
      the gratuitous None value returned by printReviews().

      What are you aiming for? If your purpose is to explore/understand
      lexical scopes, I suggest that you get it right in your head in the
      context of a simple non-recursive function, then /if necessary/ try to
      do it in a recursive class method.

      HTH,
      John




      Comment

      Working...