Are closures not supported? #2583
-
Hi. Are closures not supported? The following code all gives: Reading a variable from closure context:
=> Setting a variable in closure context:
=> |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Yes, closures are supported. Any Python code using closures will work the same if translated into Hy. Your first example doesn't work because there's no built-in macro named Your second example doesn't work because your function tries to set |
Beta Was this translation helpful? Give feedback.
-
Ok. Thanks. I'll have a look. What do you mean with the |
Beta Was this translation helpful? Give feedback.
-
It works after |
Beta Was this translation helpful? Give feedback.
Yes, closures are supported. Any Python code using closures will work the same if translated into Hy.
Your first example doesn't work because there's no built-in macro named
setf
. Note that the error message is actuallyNameError: name 'setf' is not defined
, notUnboundLocalError
.Your second example doesn't work because your function tries to set
x
, which means it will create a new local variable forx
, which is unset by the time of(+ x 1)
. Use(nonlocal x)
to avoid this. In general, I'd recommend mastering Python scoping before trying to uselet
, which complicates things.