-
Notifications
You must be signed in to change notification settings - Fork 2.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Schrödinger's variable #245
Comments
Maybe this is intuitive to other folks, but I got burned pretty badly by this one recently when writing some code that used closures. I would have thought that on the definition of |
Hi Charles, thanks for sharing this. I think the concept overlaps with The sticky output function example, but I do like the title and certain parts of your explanation. So I think the best way out is to combine these two in the next release :) |
@satwikkansal ahh, I missed that one. Merging them sounds good! Let me know if you want me to take a shot a combining the explanations. |
@charles-l Sure, that'd be helpful, thanks |
▶ Schrödinger's variable *The asterisk at the end of the title indicates the example was not present in the first release and has been recently added. funcs = []
results = []
for x in range(7):
def some_func():
return x
funcs.append(some_func)
results.append(some_func()) # note the function call here
funcs_results = [func() for func in funcs] Output (Python version): >>> results
[0, 1, 2, 3, 4, 5, 6]
>>> funcs_results
[6, 6, 6, 6, 6, 6, 6] The values of >>> powers_of_x = [lambda x: x**i for i in range(10)]
>>> [f(2) for f in powers_of_x]
[512, 512, 512, 512, 512, 512, 512, 512, 512, 512] 💡 Explanation:
>>> import inspect
>>> inspect.getclosurevals(funcs[0])
ClosureVars(nonlocals={}, globals={'x': 6}, builtins={}, unbound=set()) Since >>> x = 42
>>> [func() for func in funcs]
[42, 42, 42, 42, 42, 42, 42]
funcs = []
for x in range(7):
def some_func(x=x):
return x
funcs.append(some_func) Output: >>> funcs_results = [func() for func in funcs]
>>> funcs_results
[0, 1, 2, 3, 4, 5, 6] It is not longer using the >>> inspect.getclosurevars(funcs[0])
ClosureVars(nonlocals={}, globals={}, builtins={}, unbound=set()) |
▶ Schrödinger's variable *
The asterisk at the end of the title indicates the example was not present in the first release and has been recently added.
Output (Python version):
💡 Explanation:
Python doesn't actually bind the value of
target
inf()
. It just creates a function that will look uptarget
in the surrounding context.Since
target
will continue to be updated until it is set toNone
in the last iteration of the for loop,target=None
when it prints inside off()
Output:
This might be made a bit clearer if we use a global variable rather than a free variable:
Output.
The text was updated successfully, but these errors were encountered: