Is it true that in Python the closure will persist if and only if it is mentioned by lexicaly in the return value

Let's say I have Python2 code

def foo(n):
    bar = n
    def dispatch(exp):
        return eval(exp)
    return dispatch

foo(10)("bar * 2")  # throw NameError

      

It seems that the closure is bar

not being persisted. I am assuming it is not shown in the return function

On the other hand, if I mentioned bar

in the return function, although I did nothing, it is saved as a closure

def foo(n):
    bar = n
    def dispatch(exp):
        if bar:
            pass
        return eval(exp)
    return dispatch

foo(10)("bar * 2")  # return 20

      

Did I understand correctly? This also applies to other languages ​​that support closures, such as JavaScript, Scheme, ...

0
closures python


source to share


No one has answered this question yet

See similar questions:

226
Why are nested python functions not called closures?
3
Looking for objects in the application area

or similar:

994
How do I return multiple values ​​from a function?
683
Get unique values ​​from a list in python
473
Why is "not (true) in [False, True]" returning False?
226
Why are nested python functions not called closures?
128
Store closure as a variable in Swift
26
How do I close in Emacs Lisp?
4
Is a language with top-notch functions necessarily closable?
3
How to name the function that creates the closure
2
Tracking the number of function + closure calls (à la SICP) in Python
1
Unlimited Javascript Memorandum



All Articles
Loading...
X
Show
Funny
Dev
Pics