Skip to content

Instantly share code, notes, and snippets.

@Nurdok
Created October 3, 2013 13:04
Show Gist options
  • Select an option

  • Save Nurdok/6809485 to your computer and use it in GitHub Desktop.

Select an option

Save Nurdok/6809485 to your computer and use it in GitHub Desktop.

Revisions

  1. Nurdok created this gist Oct 3, 2013.
    38 changes: 38 additions & 0 deletions python_class_closure
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    >>> class Works(object):
    ... a = 1
    ... b = [a + x for x in range(10)]
    >>> Works.a
    0: 1
    >>> Works.b
    1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> class DoesntWork(object):
    ... a = 1
    ... b = (a + x for x in range(10))
    >>> DoesntWork.a
    2: 1
    >>> DoesntWork.b
    3: <generator object <genexpr> at 0x00000000029E2B40>
    >>> for i in DoesntWork.b:
    ... print i
    Traceback (most recent call last):
    File "<pyshell#6>", line 1, in <module>
    for i in DoesntWork.b:
    File "<pyshell#3>", line 3, in <genexpr>
    b = (a + x for x in range(10))
    NameError: global name 'a' is not defined
    >>> def foo():
    ... a = 1
    ... return list(a + x for x in xrange(10))
    >>> foo()
    4: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    >>> class DoesntWork2(object):
    ... a = 1
    ... b = list(a + x for x in range(10))
    Traceback (most recent call last):
    File "<pyshell#9>", line 1, in <module>
    class DoesntWork2(object):
    File "<pyshell#9>", line 3, in DoesntWork2
    b = list(a + x for x in range(10))
    File "<pyshell#9>", line 3, in <genexpr>
    b = list(a + x for x in range(10))
    NameError: global name 'a' is not defined