Accessing Variables Defined Inside a Closure
Problem
You would like to extend a closure with functions that allow the inner variables to be accessed and modified.
Solution
Normally, the inner variables of a closure are completely hidden to the outside world. However, you can provide access by writing accessor functions and attaching them to the closure as function attributes. For example:
defsample():n=0# Closure functiondeffunc():('n=',n)# Accessor methods for ndefget_n():returnndefset_n(value):nonlocalnn=value# Attach as function attributesfunc.get_n=get_nfunc.set_n=set_nreturnfunc
Here is an example of using this code:
>>>f=sample()>>>f()n= 0>>>f.set_n(10)>>>f()n= 10>>>f.get_n()10>>>
Discussion
There are two main features that make this Shortcut work. First,
nonlocal declarations make it possible to write functions that
change inner variables. Second, function attributes allow the
accessor methods to be attached to the closure function in a
straightforward manner where they work a lot like instance methods
(even though no class is involved).
A slight extension to this Shortcut can be made to have closures emulate instances of a class. All you need to do is copy the inner functions over to the dictionary of an instance and return it. For example:
import ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access