Creating Multiple Counters From A Single Function Using Nonlocal Statement In Python

1. instructions

  • The returned incr() function must be nested in make_counter() function
  • The nonlocal variable must be explicitly declared in the nested function
  • Only then can you modify n in the parent scope and keep the state for repeated calls
def make_counter(n):
def incr():
nonlocal n
n = n + 1
print(n)
return incr
~~~
>>> c1 = make_counter(1)
>>> c2 = make_counter(99)
>>> c1()
2
>>> c1()
3
>>> c2()
100
>>> c1()
4
  • If you omit/comment out nonlocal n in the code above you get
def make_counter(n):
def incr():
n = n + 1
print(n)
return incr

>>> c1 = make_counter(1)
>>> c1()

Traceback (most recent call last):
File "c:/Users/Admin/Documents/workspace/work.log/kb/sicp/s09_03.py", line 10, in <module>
c() # 2
File "c:/Users/Admin/Documents/workspace/work.log/kb/sicp/s09_03.py", line 4, in incr
n = n+"yyy"
UnboundLocalError: local variable 'n' referenced before assignment
The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. 
This is important because the default behavior for binding is to search the local namespace first.
The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.
Names listed in a nonlocal statement, unlike those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).
Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scope.

2. links

--

--

--

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

My Experience on Clean Code

AWS Architecture— Batch processing and Data Analytics

Choosing technologies, things to consider

Five Principles that Guide TiDB and PingCAP (Part I)

RCE via LFI Log Poisoning - The Death Potion

Open Source A/B Testing

The 4 Defining Principles of a Successful QA Testing Project

8 Guides That Will Make You a Better Programmer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

More from Medium

Byte Strings Are Decoded To ASCII In IO By Default In Python

6 Ways You Can Get Keys From a Python Dictionary

Calculate a Number Factorial in Python — pythonpip.com

Python functional programming processing functions: map () , Filter () , reduce ()