A scope is home for a function,
>>> def g(i): >>> def f(): >>> return i >>> return f >>> print [f() for f in (g(i) for i in xrange(3))] [0, 1, 2]but what is a scope for a lambda?
>>> print [f() for f in [lambda: i for i in xrange(3)]] [2, 2, 2]A scope is home for a generator,
>>> print [f() for f in (lambda: i for i in xrange(3))] [0, 1, 2]and a default parameter is a hack for a lack of a scope,
>>> print [f() for f in [lambda a=i: a for i in xrange(3)]] [0, 1, 2]but a new scope is home for a lambda.
>>> print [f() for f in ((lambda a=i: lambda: a)() for i in xrange(3))] [0, 1, 2]
And while we're on the topic of weird Python hacks and weird comprehensions.
What the heck is this?
>>> foobar = [(1, 2, 3), (4, 5), (6, 7, 8, 9), (0, )] >>> # foo are elements in bar which are elements in foobar >>> [foo for bar in foobar for foo in bar] [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]Well this was really just an excuse to rock the new syntax highlighter.
No comments:
Post a Comment