Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Python Unlocked

You're reading from   Python Unlocked Become more fluent in Python—learn strategies and techniques for smart and high-performance Python programming

Arrow left icon
Product type Paperback
Published in Dec 2015
Publisher
ISBN-13 9781785885990
Length 172 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Arun Tigeraniya Arun Tigeraniya
Author Profile Icon Arun Tigeraniya
Arun Tigeraniya
Arrow right icon
View More author details
Toc

Functions with state – closures


Key 2: Creating cheap state-remembering functions.

A closure is a function that has access to variables in an enclosing scope, which has completed its execution. This means that referenced objects are kept alive until the function is in memory. The main utility of such a setup is to easily retain some state, or to create specialized functions whose functioning depends on the initial setup:

>>> def getformatter(start,end):
...     def formatter(istr):
...         print("%s%s%s"%(start,istr,end))
...     return formatter
... 
>>> formatter1 = getformatter("<",">")
>>> formatter2 = getformatter("[","]")
>>> 
>>> formatter1("hello")
<hello>
>>> formatter2("hello")
[hello]
>>> formatter1.__closure__[0].cell_contents
'>'
>>> formatter1.__closure__[1].cell_contents
'<'

We can do the same by creating a class and using the instance object to save state. The benefit with closures...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image