Skip to content

Instantly share code, notes, and snippets.

@leetrout
Created October 25, 2019 16:19
Show Gist options
  • Save leetrout/d765b75979b744fac52f8c106f4bde14 to your computer and use it in GitHub Desktop.
Save leetrout/d765b75979b744fac52f8c106f4bde14 to your computer and use it in GitHub Desktop.
Python Comprehensions Behavior
things = {
"foo": "bar",
"baz": "bing",
}
for k, v in things.items():
pass
print("k leaked: " + k)
[(k2, v2) for k2, v2 in things.items()]
print("k2 leaked: " + k2)
{k3: v3 for k3, v3 in things.items()}
try:
msg = "k3 didn't leak: " + k3
except NameError as e:
print("k3 didn't leak: " + str(e))
def foo(*args):
print("foo was called with " + str(args))
print("test call to foo")
foo(1, 2, 3, 4)
print("generators are lazy")
(foo(k4, v4) for k4, v4 in things.items())
print("unless you eval them")
list((foo(k4, v4) for k4, v4 in things.items()))
$jython main.py
k leaked: baz
k2 leaked: baz
k3 didn't leak: name 'k3' is not defined
test call to foo
foo was called with (1, 2, 3, 4)
generators are lazy
unless you eval them
foo was called with ('foo', 'bar')
foo was called with ('baz', 'bing')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment