SlideShare a Scribd company logo
Decorators Explained 
A Powerful Tool That Should Be in Your Python Toolbelt
Samuel Fortier-Galarneau 
Software Developer @ Digium, Inc 
@samuelg 
http://github.com/samuelg
Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.
Agenda 
• Primer 
• What is a decorator? 
• How do they work? 
• Examples
Primer 
Functions 
• Functions in Python are first class members 
• They can be passed to other functions and return 
new functions 
def add(first, second): 
return first + second 
def partial(func, first): 
def wrapper(second): 
return func(first, second) 
return wrapper
Primer 
Functions 
>>> func = partial(add, 1) 
>>> func(2) 
3
Primer 
Variable function arguments 
• Functions can have variable positional and 
keyword arguments via *args and **kwargs 
• *args and **kwargs can be packed again and 
passed along to another function 
def func(*args, **kwargs): 
print args 
print kwargs
Primer 
Variable function arguments 
>>> func(1, 2, my_arg=‘value') 
(1, 2) 
{'my_arg': 'value'}
Primer 
Variable function arguments 
def func(*args, **kwargs): 
other_func(*args, **kwargs) 
def other_func(arg1, arg2, arg3): 
print arg1 
print arg2 
print arg3
Primer 
Variable function arguments 
>>> func(1, 2, arg3=3) 
1 
2 
3
What is a decorator? 
• Injects code before/after a function call or object 
creation 
• A callable wrapper around a callable resource 
(object that implements __call__ is callable) 
• Similar to macros in C/C++ but uses built in 
Python syntax and language semantics
What is a decorator? 
• Can be implemented as a function or a class 
• Can be applied to a function or a class 
• Functions have an implicit __call__ method which 
makes them callable 
• Classes must implement a __call__ method to 
qualify as a decorator
How do they work? 
Decorator function 
def decorator(func): 
def wrapper(): 
print 'in wrapper()' 
return func() 
return wrapper 
@decorator 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function 
>>> my_function() 
in wrapper() 
in my_function()
How do they work? 
Decorator function 
def decorator(func): 
def wrapper(): 
print 'in wrapper()' 
return func() 
return wrapper 
@decorator 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function 
def decorator(func): 
def wrapper(): 
print 'in wrapper()' 
return func() 
return wrapper 
@decorator 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function 
def decorator(func): 
def wrapper(): 
print 'in wrapper()' 
return func() 
return wrapper 
@decorator 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function 
def decorator(func): 
def wrapper(): 
print 'in wrapper()' 
return func() 
return wrapper 
@decorator 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function 
wrapper is a closure over func 
def decorator(func): 
def wrapper(): 
print 'in wrapper()' 
return func() 
return wrapper 
@decorator 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function 
def decorator(func): 
def wrapper(): 
print 'in wrapper()' 
return func() 
return wrapper 
@decorator 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator class 
class Decorator(object): 
def __init__(self, func): 
self.func = func 
def __call__(self): 
print 'in __call__()' 
return self.func() 
@Decorator 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator class 
>>> my_function() 
in __call__() 
in my_function()
How do they work? 
Decorator function with arguments 
def decorator(*args, **kwargs): 
def receiver(func): 
def wrapper(): 
print 'in wrapper()' 
print args 
print kwargs 
return func() 
return wrapper 
return receiver 
@decorator(1, config='value') 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function with arguments 
>>> my_function() 
in wrapper() 
(1,) 
{'config': 'value'} 
in my_function()
How do they work? 
Decorator function with arguments 
def decorator(*args, **kwargs): 
def receiver(func): 
def wrapper(): 
print 'in wrapper()' 
print args 
print kwargs 
return func() 
return wrapper 
return receiver 
@decorator(1, config='value') 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function with arguments 
def decorator(*args, **kwargs): 
def receiver(func): 
def wrapper(): 
print 'in wrapper()' 
print args 
print kwargs 
return func() 
return wrapper 
return receiver 
@decorator(1, config='value') 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function with arguments 
def decorator(*args, **kwargs): 
def receiver(func): 
def wrapper(): 
print 'in wrapper()' 
print args 
print kwargs 
return func() 
return wrapper 
return receiver 
@decorator(1, config='value') 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function with arguments 
def decorator(*args, **kwargs): 
def receiver(func): 
def wrapper(): 
print 'in wrapper()' 
print args 
print kwargs 
return func() 
return wrapper 
return receiver 
@decorator(1, config='value') 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function with arguments 
def decorator(*args, **kwargs): 
def receiver(func): 
def wrapper(): 
print 'in wrapper()' 
print args 
print kwargs 
return func() 
return wrapper 
return receiver 
@decorator(1, config='value') 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function with arguments 
def decorator(*args, **kwargs): 
def receiver(func): 
def wrapper(): 
print 'in wrapper()' 
print args 
print kwargs 
return func() 
return wrapper 
return receiver 
@decorator(1, config='value') 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function with arguments 
def decorator(*args, **kwargs): 
def receiver(func): 
def wrapper(): 
print 'in wrapper()' 
print args 
print kwargs 
return func() 
return wrapper 
return receiver 
@decorator(1, config='value') 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator function with arguments 
def decorator(*args, **kwargs): 
def receiver(func): 
def wrapper(): 
print 'in wrapper()' 
print args 
print kwargs 
return func() 
return wrapper 
return receiver 
@decorator(1, config='value') 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator class with arguments 
class Decorator(object): 
def __init__(self, *args, **kwargs): 
self.args = args 
self.kwargs = kwargs 
def __call__(self, func): 
def wrapper(): 
print 'in __call__()' 
print self.args 
print self.kwargs 
return func() 
return wrapper 
@Decorator(1, config='value') 
def my_function(): 
print 'in my_function()'
How do they work? 
Decorator class with arguments 
>>> my_function() 
in __call__() 
(1,) 
{'config': 'value'} 
in my_function()
Example: counting function 
calls 
class Counter(object): 
def __init__(self, func): 
self.count = 0 
self.func = func 
def __call__(self): 
self.count += 1 
return self.func() 
def getCount(self): 
return self.count 
@Counter 
def function(): 
pass
Example: counting function 
calls 
>>> function() 
>>> function() 
>>> function() 
>>> function.getCount() 
3
Example: memoize 
class Memoize(object): 
def __init__(self, func): 
self.cache = {} 
self.func = func 
def __call__(self, *args, **kwargs): 
cache_key = '%s%s' % (args, kwargs) 
if cache_key in self.cache: 
return self.cache[cache_key] 
else: 
result = self.func(*args, **kwargs) 
self.cache[cache_key] = result 
return result 
@Memoize 
def function(bound): 
sum = 0 
for x in range(bound): 
sum += x 
return sum
Example: memoize 
>>> function(100000000) 
~ 11 seconds 
>>> function(100000000) 
~ 10 milliseconds
Example: type checker 
def type_check(*types): 
def receiver(func): 
def wrapper(*args, **kwargs): 
for index, type_arg in enumerate(types): 
if type(args[index]) != type_arg: 
raise TypeError('Expected %s at index %s' % 
(type_arg, index)) 
return func(*args, **kwargs) 
return wrapper 
return receiver 
@type_check(int, int, str) 
def function(first, second, third): 
print 'success'
Example: type checker 
>>> function(1, 2, ‘works') 
success 
>>> function('will', 'not', ‘work') 
Traceback (most recent call last): 
File "type.py", line 17, in <module> 
function('will', 'not', 'work') 
File "type.py", line 7, in wrapper 
raise TypeError('Expected %s at index %s' % 
(type_arg, index)) 
TypeError: Expected <type 'int'> at index 0
Example: singleton 
instances = {} 
def singleton(cls): 
def create(*args): 
if cls not in instances: 
instances[cls] = cls(*args) 
return instances[cls] 
return create 
@singleton 
class Toolbelt(object): 
def __init__(self): 
pass
Example: singleton 
>>> toolbelt = Toolbelt() 
>>> another = Toolbelt() 
>>> another == toolbelt 
True
Other uses 
• Retries 
• Pre/Post conditions 
• Function input/output transforms 
• Performance logging 
• Authorization
Thanks! 
Samuel Fortier-Galarneau 
@samuelg 
http://github.com/samuelg 
http://www.slideshare.net/sgalarne/decorators-2

More Related Content

PDF
Python decorators
PPTX
Advanced Python : Decorators
PDF
Friend function in c++
PPTX
Python decorators
PPTX
Templates in C++
ODP
Decorators in Python
PPTX
Iterarators and generators in python
PDF
Strings in java
Python decorators
Advanced Python : Decorators
Friend function in c++
Python decorators
Templates in C++
Decorators in Python
Iterarators and generators in python
Strings in java

What's hot (20)

PPTX
Pointer in c
PPTX
Java exception handling
PPT
Python GUI Programming
PDF
Pointers in C
PPTX
File Handling Python
PPTX
Python: Modules and Packages
PPTX
INLINE FUNCTION IN C++
PDF
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
PPTX
Values and Data types in python
PPT
C++: Constructor, Copy Constructor and Assignment operator
PDF
Python programming : Classes objects
PPTX
Hash table in java
PPTX
Modules in Python Programming
PPT
friend function(c++)
PPTX
Inheritance in c++
PPT
Java collections concept
PPTX
collection framework in java
PPTX
Functions in Python
PPTX
Python-Encapsulation.pptx
PPTX
Java abstract class & abstract methods
Pointer in c
Java exception handling
Python GUI Programming
Pointers in C
File Handling Python
Python: Modules and Packages
INLINE FUNCTION IN C++
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 2
Values and Data types in python
C++: Constructor, Copy Constructor and Assignment operator
Python programming : Classes objects
Hash table in java
Modules in Python Programming
friend function(c++)
Inheritance in c++
Java collections concept
collection framework in java
Functions in Python
Python-Encapsulation.pptx
Java abstract class & abstract methods
Ad

Viewers also liked (20)

PDF
EuroPython 2015 - Decorators demystified
PDF
The (unknown) collections module
PDF
An Introduction to Object-Oriented Programming (DrupalCamp North 2015)
PDF
Oop concepts classes_objects
PDF
Message-passing concurrency in Python
PDF
Meta-Classes in Python
PDF
Multiprocessing with python
PDF
Interfacing C/C++ and Python with SWIG
PDF
NETCONF Call Home
PDF
Python in Action (Part 1)
PPTX
Prepping the Analytics organization for Artificial Intelligence evolution
PDF
Mastering Python 3 I/O (Version 2)
PDF
Generators: The Final Frontier
PPTX
DockerCon EU 2015: Persistent, stateful services with docker cluster, namespa...
PDF
Django Best Practices
PDF
An Introduction to Python Concurrency
PDF
QCon Rio - Machine Learning for Everyone
PDF
Python for Image Understanding: Deep Learning with Convolutional Neural Nets
PPTX
Tutorial on Deep learning and Applications
PDF
Python Generator Hacking
EuroPython 2015 - Decorators demystified
The (unknown) collections module
An Introduction to Object-Oriented Programming (DrupalCamp North 2015)
Oop concepts classes_objects
Message-passing concurrency in Python
Meta-Classes in Python
Multiprocessing with python
Interfacing C/C++ and Python with SWIG
NETCONF Call Home
Python in Action (Part 1)
Prepping the Analytics organization for Artificial Intelligence evolution
Mastering Python 3 I/O (Version 2)
Generators: The Final Frontier
DockerCon EU 2015: Persistent, stateful services with docker cluster, namespa...
Django Best Practices
An Introduction to Python Concurrency
QCon Rio - Machine Learning for Everyone
Python for Image Understanding: Deep Learning with Convolutional Neural Nets
Tutorial on Deep learning and Applications
Python Generator Hacking
Ad

Similar to Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt. (20)

PDF
PyCon NZ 2013 - Advanced Methods For Creating Decorators
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
PPTX
Python_Functions_Unit1.pptx
PDF
The Ring programming language version 1.7 book - Part 35 of 196
PPTX
Decorators.pptx
PPTX
JNTUK python programming python unit 3.pptx
PDF
Currying and Partial Function Application (PFA)
KEY
DjangoCon US 2011 - Monkeying around at New Relic
KEY
Djangocon11: Monkeying around at New Relic
PPT
25-functions.ppt
PPTX
Functions in Python Programming Language
PDF
Functions in python
PPT
Php Reusing Code And Writing Functions
PDF
Python decorators (中文)
PPTX
2 Functions2.pptx
PDF
Funkcija, objekt, python
KEY
(map Clojure everyday-tasks)
PPTX
UNIT- 2 PPDS R20.pptx
PDF
Metaprogramovanie #1
PyCon NZ 2013 - Advanced Methods For Creating Decorators
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
Python_Functions_Unit1.pptx
The Ring programming language version 1.7 book - Part 35 of 196
Decorators.pptx
JNTUK python programming python unit 3.pptx
Currying and Partial Function Application (PFA)
DjangoCon US 2011 - Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
25-functions.ppt
Functions in Python Programming Language
Functions in python
Php Reusing Code And Writing Functions
Python decorators (中文)
2 Functions2.pptx
Funkcija, objekt, python
(map Clojure everyday-tasks)
UNIT- 2 PPDS R20.pptx
Metaprogramovanie #1

Recently uploaded (20)

PDF
KodekX | Application Modernization Development
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
KodekX | Application Modernization Development
Mobile App Security Testing_ A Comprehensive Guide.pdf
Electronic commerce courselecture one. Pdf
cuic standard and advanced reporting.pdf
Empathic Computing: Creating Shared Understanding
Chapter 3 Spatial Domain Image Processing.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Spectral efficient network and resource selection model in 5G networks
Machine learning based COVID-19 study performance prediction
Digital-Transformation-Roadmap-for-Companies.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Dropbox Q2 2025 Financial Results & Investor Presentation
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Approach and Philosophy of On baking technology
Network Security Unit 5.pdf for BCA BBA.
20250228 LYD VKU AI Blended-Learning.pptx

Decorators Explained: A Powerful Tool That Should Be in Your Python Toolbelt.

  • 1. Decorators Explained A Powerful Tool That Should Be in Your Python Toolbelt
  • 2. Samuel Fortier-Galarneau Software Developer @ Digium, Inc @samuelg http://github.com/samuelg
  • 4. Agenda • Primer • What is a decorator? • How do they work? • Examples
  • 5. Primer Functions • Functions in Python are first class members • They can be passed to other functions and return new functions def add(first, second): return first + second def partial(func, first): def wrapper(second): return func(first, second) return wrapper
  • 6. Primer Functions >>> func = partial(add, 1) >>> func(2) 3
  • 7. Primer Variable function arguments • Functions can have variable positional and keyword arguments via *args and **kwargs • *args and **kwargs can be packed again and passed along to another function def func(*args, **kwargs): print args print kwargs
  • 8. Primer Variable function arguments >>> func(1, 2, my_arg=‘value') (1, 2) {'my_arg': 'value'}
  • 9. Primer Variable function arguments def func(*args, **kwargs): other_func(*args, **kwargs) def other_func(arg1, arg2, arg3): print arg1 print arg2 print arg3
  • 10. Primer Variable function arguments >>> func(1, 2, arg3=3) 1 2 3
  • 11. What is a decorator? • Injects code before/after a function call or object creation • A callable wrapper around a callable resource (object that implements __call__ is callable) • Similar to macros in C/C++ but uses built in Python syntax and language semantics
  • 12. What is a decorator? • Can be implemented as a function or a class • Can be applied to a function or a class • Functions have an implicit __call__ method which makes them callable • Classes must implement a __call__ method to qualify as a decorator
  • 13. How do they work? Decorator function def decorator(func): def wrapper(): print 'in wrapper()' return func() return wrapper @decorator def my_function(): print 'in my_function()'
  • 14. How do they work? Decorator function >>> my_function() in wrapper() in my_function()
  • 15. How do they work? Decorator function def decorator(func): def wrapper(): print 'in wrapper()' return func() return wrapper @decorator def my_function(): print 'in my_function()'
  • 16. How do they work? Decorator function def decorator(func): def wrapper(): print 'in wrapper()' return func() return wrapper @decorator def my_function(): print 'in my_function()'
  • 17. How do they work? Decorator function def decorator(func): def wrapper(): print 'in wrapper()' return func() return wrapper @decorator def my_function(): print 'in my_function()'
  • 18. How do they work? Decorator function def decorator(func): def wrapper(): print 'in wrapper()' return func() return wrapper @decorator def my_function(): print 'in my_function()'
  • 19. How do they work? Decorator function wrapper is a closure over func def decorator(func): def wrapper(): print 'in wrapper()' return func() return wrapper @decorator def my_function(): print 'in my_function()'
  • 20. How do they work? Decorator function def decorator(func): def wrapper(): print 'in wrapper()' return func() return wrapper @decorator def my_function(): print 'in my_function()'
  • 21. How do they work? Decorator class class Decorator(object): def __init__(self, func): self.func = func def __call__(self): print 'in __call__()' return self.func() @Decorator def my_function(): print 'in my_function()'
  • 22. How do they work? Decorator class >>> my_function() in __call__() in my_function()
  • 23. How do they work? Decorator function with arguments def decorator(*args, **kwargs): def receiver(func): def wrapper(): print 'in wrapper()' print args print kwargs return func() return wrapper return receiver @decorator(1, config='value') def my_function(): print 'in my_function()'
  • 24. How do they work? Decorator function with arguments >>> my_function() in wrapper() (1,) {'config': 'value'} in my_function()
  • 25. How do they work? Decorator function with arguments def decorator(*args, **kwargs): def receiver(func): def wrapper(): print 'in wrapper()' print args print kwargs return func() return wrapper return receiver @decorator(1, config='value') def my_function(): print 'in my_function()'
  • 26. How do they work? Decorator function with arguments def decorator(*args, **kwargs): def receiver(func): def wrapper(): print 'in wrapper()' print args print kwargs return func() return wrapper return receiver @decorator(1, config='value') def my_function(): print 'in my_function()'
  • 27. How do they work? Decorator function with arguments def decorator(*args, **kwargs): def receiver(func): def wrapper(): print 'in wrapper()' print args print kwargs return func() return wrapper return receiver @decorator(1, config='value') def my_function(): print 'in my_function()'
  • 28. How do they work? Decorator function with arguments def decorator(*args, **kwargs): def receiver(func): def wrapper(): print 'in wrapper()' print args print kwargs return func() return wrapper return receiver @decorator(1, config='value') def my_function(): print 'in my_function()'
  • 29. How do they work? Decorator function with arguments def decorator(*args, **kwargs): def receiver(func): def wrapper(): print 'in wrapper()' print args print kwargs return func() return wrapper return receiver @decorator(1, config='value') def my_function(): print 'in my_function()'
  • 30. How do they work? Decorator function with arguments def decorator(*args, **kwargs): def receiver(func): def wrapper(): print 'in wrapper()' print args print kwargs return func() return wrapper return receiver @decorator(1, config='value') def my_function(): print 'in my_function()'
  • 31. How do they work? Decorator function with arguments def decorator(*args, **kwargs): def receiver(func): def wrapper(): print 'in wrapper()' print args print kwargs return func() return wrapper return receiver @decorator(1, config='value') def my_function(): print 'in my_function()'
  • 32. How do they work? Decorator function with arguments def decorator(*args, **kwargs): def receiver(func): def wrapper(): print 'in wrapper()' print args print kwargs return func() return wrapper return receiver @decorator(1, config='value') def my_function(): print 'in my_function()'
  • 33. How do they work? Decorator class with arguments class Decorator(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __call__(self, func): def wrapper(): print 'in __call__()' print self.args print self.kwargs return func() return wrapper @Decorator(1, config='value') def my_function(): print 'in my_function()'
  • 34. How do they work? Decorator class with arguments >>> my_function() in __call__() (1,) {'config': 'value'} in my_function()
  • 35. Example: counting function calls class Counter(object): def __init__(self, func): self.count = 0 self.func = func def __call__(self): self.count += 1 return self.func() def getCount(self): return self.count @Counter def function(): pass
  • 36. Example: counting function calls >>> function() >>> function() >>> function() >>> function.getCount() 3
  • 37. Example: memoize class Memoize(object): def __init__(self, func): self.cache = {} self.func = func def __call__(self, *args, **kwargs): cache_key = '%s%s' % (args, kwargs) if cache_key in self.cache: return self.cache[cache_key] else: result = self.func(*args, **kwargs) self.cache[cache_key] = result return result @Memoize def function(bound): sum = 0 for x in range(bound): sum += x return sum
  • 38. Example: memoize >>> function(100000000) ~ 11 seconds >>> function(100000000) ~ 10 milliseconds
  • 39. Example: type checker def type_check(*types): def receiver(func): def wrapper(*args, **kwargs): for index, type_arg in enumerate(types): if type(args[index]) != type_arg: raise TypeError('Expected %s at index %s' % (type_arg, index)) return func(*args, **kwargs) return wrapper return receiver @type_check(int, int, str) def function(first, second, third): print 'success'
  • 40. Example: type checker >>> function(1, 2, ‘works') success >>> function('will', 'not', ‘work') Traceback (most recent call last): File "type.py", line 17, in <module> function('will', 'not', 'work') File "type.py", line 7, in wrapper raise TypeError('Expected %s at index %s' % (type_arg, index)) TypeError: Expected <type 'int'> at index 0
  • 41. Example: singleton instances = {} def singleton(cls): def create(*args): if cls not in instances: instances[cls] = cls(*args) return instances[cls] return create @singleton class Toolbelt(object): def __init__(self): pass
  • 42. Example: singleton >>> toolbelt = Toolbelt() >>> another = Toolbelt() >>> another == toolbelt True
  • 43. Other uses • Retries • Pre/Post conditions • Function input/output transforms • Performance logging • Authorization
  • 44. Thanks! Samuel Fortier-Galarneau @samuelg http://github.com/samuelg http://www.slideshare.net/sgalarne/decorators-2