SlideShare a Scribd company logo
1 of 22
Download to read offline
Decorators in Python
Haim Michael
May 19th
, 2020
All logos, trade marks and brand names used in this presentation belong
to the respective owners.
© 2020 life michael
Decorators Basics
© 2020 life michael
Introduction
 The decorator allows us to add new functionality to existing
object without modifying its structure.
 When decorating a function, the decoration is invoked
before the definition of the function takes place.
@decorator
def decorated(): pass
is indirectly changed into
decorator(decorated)
© 2020 life michael
Jump Start
 The simples way to develop a decorator would be to
develop a function that has one parameter to which a
function is passed over.
 Whenever our decorator is invoked (enough to have in our
code @ourdecorator to invoke the decorator) the decorated
function will be passed over to our decorator.
© 2020 life michael
Jump Start
 The decorator function should include the definition of
another function, the decorator function returns. That other
inner function usually invokes the decorated function.
 The function returned by our decorator will take the place of
the decorated function. Every call to the decorated function
in our code will be replaced by a call to the function returned
by our decorator.
© 2020 life michael
Jump Start
def uppercase(func):
print("2")
def inner():
print("4")
data = func()
return data.upper()
return inner
print("9")
@uppercase
def getGreeting():
print("13")
return "good morning"
print("16")
print(getGreeting())
© 2020 life michael
Decorating Function with Parameters
 In order to decorate a function with parameter(s) we just
need make sure the function returned by the decorator has
the same parameter(s) accordingly.
© 2020 life michael
Decorating Function with Parameters
def uppercase(func):
print("2")
def inner(nickname):
print("4")
data = func(nickname)
return data.upper()
return inner
print("9")
@uppercase
def getGreeting(nickname):
print("13")
return "good morning " + nickname
print("16")
print(getGreeting("dave"))
© 2020 life michael
Using a Class as Decorator
 The decorator should be a callable object. It can be a
function. I can also be a class we define together with the
__init__ and the __call__.
© 2020 life michael
Using a Class as Decorator
class uppercase:
def __init__(self, f):
self.f = f
def __call__(self, nickname):
return self.f(nickname).upper()
@uppercase
def greet(nickname):
return "good morning " + nickname
print(greet("danny"))
© 2020 life michael
Decorators Nesting
 We can place together more than one decorator. Doing so,
we should imagine the decorators execution one after the
other in the order in which they are listed (top to bottom).
 The output of each decorator execution is the input for the
decorator above.
© 2020 life michael
Decorators Nesting
def uppercase(func):
def inner(nickname):
data = func(nickname)
return data.upper()
return inner
def stars(func):
def inner(text):
input = func(text)
return "*** "+input+" ***"
return inner
@stars
@uppercase
def getGreeting(nickname):
return "good morning " + nickname
print(getGreeting("dave"))
© 2020 life michael
Class Decorators
 We can develop a decorator for classes. The object that
represents a class is also a factory function that is called
whenever a new object is created.
def bang(func):
def inner():
print("bang!!!")
ob = func()
return ob
return inner
@bang
class Rectangle(): pass
ob1 = Rectangle()
ob2 = Rectangle()
© 2020 life michael
Decorators with Arguments
 We can develop a decorator that takes arguments when
called.
def bang(text):
def f(func):
def inner():
print(text)
ob = func()
return ob
return inner
return f
@bang(text="Picaso")
def Rectangle(): pass
ob1 = Rectangle()
ob2 = Rectangle()
© 2020 life michael
Stateful Decorators
 We can develop a decorator that keeps tracking of a state
by using attributes we add to the object that represents the
decorator.
def counter(text):
if not hasattr(counter,"classes"):
counter.classes = dict()
if text not in counter.classes:
counter.classes[text] = 0
def f(func):
def inner():
counter.classes[text] = int(counter.classes[text]) + 1
ob = func()
return ob
return inner
return f
© 2020 life michael
Stateful Decorators
@counter("Rectangle")
class Rectangle(): pass
@counter("Circle")
class Circle(): pass
rec1 = Rectangle()
rec2 = Rectangle()
rec3 = Rectangle()
circ1 = Circle()
circ2 = Circle()
print(counter.classes["Rectangle"])
print(counter.classes["Circle"])
© 2020 life michael
Real World Examples
© 2020 life michael
Measuring Execution Time
 We can easily develop a decorator for the purpose of
measuring the execution time of specific functions.
import time
def stopper(func):
def inner(times):
start = time.perf_counter()
value = func(times)
end = time.perf_counter()
run = end - start
print("running_time=",run)
return value
return inner
@stopper
def doSomething(times):
total = 0
for i in range(times):
total += i
return total
doSomething(99999)
© 2020 life michael
Debugging & Logging
 We can easily develop a decorator that will track each and
every execution of a specific function.
def tinylog(func):
def f(*args, **kwargs):
args1 = [repr(a) for a in args]
args2 = [repr(k)+":"+repr(v) for k, v in kwargs.items()]
value = func(*args, **kwargs)
print("calling ", func.__name__, " ", repr(args1), " ",
repr(args2), " returns ", value)
return value
return f
@tinylog
def total(a,b):
return a+b
print(total(3,4))
print(total(5,5))
print(total(8,7))
© 2020 life michael
Libraries Development
 We can easily create decorators for functions and classes
as part of a library for other developers.
 There are many libraries that employ the power of
decorators in their service, including ORM libraries (e.g.
PonyORM), Unit Testing libraries (e.g. Testify) and others.
© 2020 life michael
Caching Data
 Assuming that we have a function that fetches data from the
server we can develop a decorator that will provide us with
an caching mechanism.
© 2020 life michael
Questions & Answers
 Thanks for attending this meetup.

More Related Content

What's hot

Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }John De Goes
 
Database performance 101
Database performance 101Database performance 101
Database performance 101Leon Fayer
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteDirkjan Bussink
 
ZipCode_Distance_by_Agent_Home_Zip_2015091501
ZipCode_Distance_by_Agent_Home_Zip_2015091501ZipCode_Distance_by_Agent_Home_Zip_2015091501
ZipCode_Distance_by_Agent_Home_Zip_2015091501Robert Davis
 
The Ring programming language version 1.5.4 book - Part 23 of 185
The Ring programming language version 1.5.4 book - Part 23 of 185The Ring programming language version 1.5.4 book - Part 23 of 185
The Ring programming language version 1.5.4 book - Part 23 of 185Mahmoud Samir Fayed
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to ArraysTareq Hasan
 
Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...
Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...
Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...Andrea Lazzarotto
 
intro_to_python_20150825
intro_to_python_20150825intro_to_python_20150825
intro_to_python_20150825Shung-Hsi Yu
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java languageHareem Naz
 
The Ring programming language version 1.5.2 book - Part 52 of 181
The Ring programming language version 1.5.2 book - Part 52 of 181The Ring programming language version 1.5.2 book - Part 52 of 181
The Ring programming language version 1.5.2 book - Part 52 of 181Mahmoud Samir Fayed
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212Mahmoud Samir Fayed
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10Vince Vo
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patternsTomasz Kowal
 

What's hot (20)

Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
Database performance 101
Database performance 101Database performance 101
Database performance 101
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Lecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of TwenteLecture on Rubinius for Compiler Construction at University of Twente
Lecture on Rubinius for Compiler Construction at University of Twente
 
ZipCode_Distance_by_Agent_Home_Zip_2015091501
ZipCode_Distance_by_Agent_Home_Zip_2015091501ZipCode_Distance_by_Agent_Home_Zip_2015091501
ZipCode_Distance_by_Agent_Home_Zip_2015091501
 
The Ring programming language version 1.5.4 book - Part 23 of 185
The Ring programming language version 1.5.4 book - Part 23 of 185The Ring programming language version 1.5.4 book - Part 23 of 185
The Ring programming language version 1.5.4 book - Part 23 of 185
 
Java: Introduction to Arrays
Java: Introduction to ArraysJava: Introduction to Arrays
Java: Introduction to Arrays
 
Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...
Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...
Data Visualization — Le funzionalità matematiche di Sage per la visualizzazio...
 
intro_to_python_20150825
intro_to_python_20150825intro_to_python_20150825
intro_to_python_20150825
 
C Prog - Array
C Prog - ArrayC Prog - Array
C Prog - Array
 
C++ examples &revisions
C++ examples &revisionsC++ examples &revisions
C++ examples &revisions
 
Arrays in java language
Arrays in java languageArrays in java language
Arrays in java language
 
Arrays
ArraysArrays
Arrays
 
The Ring programming language version 1.5.2 book - Part 52 of 181
The Ring programming language version 1.5.2 book - Part 52 of 181The Ring programming language version 1.5.2 book - Part 52 of 181
The Ring programming language version 1.5.2 book - Part 52 of 181
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212The Ring programming language version 1.10 book - Part 31 of 212
The Ring programming language version 1.10 book - Part 31 of 212
 
C# p9
C# p9C# p9
C# p9
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10
 
Very basic functional design patterns
Very basic functional design patternsVery basic functional design patterns
Very basic functional design patterns
 

Similar to The Power of Decorators in Python [Meetup]

Python decorators
Python decoratorsPython decorators
Python decoratorsAlex Su
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingDamian T. Gordon
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
The Ring programming language version 1.5.1 book - Part 20 of 180
The Ring programming language version 1.5.1 book - Part 20 of 180The Ring programming language version 1.5.1 book - Part 20 of 180
The Ring programming language version 1.5.1 book - Part 20 of 180Mahmoud Samir Fayed
 
Monads in python
Monads in pythonMonads in python
Monads in pythoneldariof
 
The Ring programming language version 1.2 book - Part 27 of 84
The Ring programming language version 1.2 book - Part 27 of 84The Ring programming language version 1.2 book - Part 27 of 84
The Ring programming language version 1.2 book - Part 27 of 84Mahmoud Samir Fayed
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdfpaijitk
 
Drinking the free kool-aid
Drinking the free kool-aidDrinking the free kool-aid
Drinking the free kool-aidDavid Hoyt
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181Mahmoud Samir Fayed
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 

Similar to The Power of Decorators in Python [Meetup] (20)

Python decorators
Python decoratorsPython decorators
Python decorators
 
Decorators.pptx
Decorators.pptxDecorators.pptx
Decorators.pptx
 
Python Decorators
Python DecoratorsPython Decorators
Python Decorators
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented Programming
 
Refactoring
RefactoringRefactoring
Refactoring
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Refactoring
RefactoringRefactoring
Refactoring
 
The Ring programming language version 1.5.1 book - Part 20 of 180
The Ring programming language version 1.5.1 book - Part 20 of 180The Ring programming language version 1.5.1 book - Part 20 of 180
The Ring programming language version 1.5.1 book - Part 20 of 180
 
Monads in python
Monads in pythonMonads in python
Monads in python
 
Python speleology
Python speleologyPython speleology
Python speleology
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
compose_speaker_session.pdf
compose_speaker_session.pdfcompose_speaker_session.pdf
compose_speaker_session.pdf
 
The Ring programming language version 1.2 book - Part 27 of 84
The Ring programming language version 1.2 book - Part 27 of 84The Ring programming language version 1.2 book - Part 27 of 84
The Ring programming language version 1.2 book - Part 27 of 84
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
 
Drinking the free kool-aid
Drinking the free kool-aidDrinking the free kool-aid
Drinking the free kool-aid
 
The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181The Ring programming language version 1.5.2 book - Part 37 of 181
The Ring programming language version 1.5.2 book - Part 37 of 181
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 

More from Haim Michael

Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in JavaHaim Michael
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design PatternsHaim Michael
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL InjectionsHaim Michael
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in JavaHaim Michael
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design PatternsHaim Michael
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in PythonHaim Michael
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in PythonHaim Michael
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScriptHaim Michael
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214Haim Michael
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump StartHaim Michael
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHPHaim Michael
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9Haim Michael
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on SteroidHaim Michael
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib LibraryHaim Michael
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908Haim Michael
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818Haim Michael
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728Haim Michael
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Haim Michael
 

More from Haim Michael (20)

Anti Patterns
Anti PatternsAnti Patterns
Anti Patterns
 
Virtual Threads in Java
Virtual Threads in JavaVirtual Threads in Java
Virtual Threads in Java
 
MongoDB Design Patterns
MongoDB Design PatternsMongoDB Design Patterns
MongoDB Design Patterns
 
Introduction to SQL Injections
Introduction to SQL InjectionsIntroduction to SQL Injections
Introduction to SQL Injections
 
Record Classes in Java
Record Classes in JavaRecord Classes in Java
Record Classes in Java
 
Microservices Design Patterns
Microservices Design PatternsMicroservices Design Patterns
Microservices Design Patterns
 
Structural Pattern Matching in Python
Structural Pattern Matching in PythonStructural Pattern Matching in Python
Structural Pattern Matching in Python
 
Unit Testing in Python
Unit Testing in PythonUnit Testing in Python
Unit Testing in Python
 
OOP Best Practices in JavaScript
OOP Best Practices in JavaScriptOOP Best Practices in JavaScript
OOP Best Practices in JavaScript
 
Java Jump Start
Java Jump StartJava Jump Start
Java Jump Start
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
 
Bootstrap Jump Start
Bootstrap Jump StartBootstrap Jump Start
Bootstrap Jump Start
 
What is new in PHP
What is new in PHPWhat is new in PHP
What is new in PHP
 
What is new in Python 3.9
What is new in Python 3.9What is new in Python 3.9
What is new in Python 3.9
 
Programming in Python on Steroid
Programming in Python on SteroidProgramming in Python on Steroid
Programming in Python on Steroid
 
The matplotlib Library
The matplotlib LibraryThe matplotlib Library
The matplotlib Library
 
Pandas meetup 20200908
Pandas meetup 20200908Pandas meetup 20200908
Pandas meetup 20200908
 
The num py_library_20200818
The num py_library_20200818The num py_library_20200818
The num py_library_20200818
 
Jupyter notebook 20200728
Jupyter notebook 20200728Jupyter notebook 20200728
Jupyter notebook 20200728
 
Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start) Node.js Crash Course (Jump Start)
Node.js Crash Course (Jump Start)
 

Recently uploaded

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 

Recently uploaded (20)

What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 

The Power of Decorators in Python [Meetup]

  • 1. Decorators in Python Haim Michael May 19th , 2020 All logos, trade marks and brand names used in this presentation belong to the respective owners.
  • 2. © 2020 life michael Decorators Basics
  • 3. © 2020 life michael Introduction  The decorator allows us to add new functionality to existing object without modifying its structure.  When decorating a function, the decoration is invoked before the definition of the function takes place. @decorator def decorated(): pass is indirectly changed into decorator(decorated)
  • 4. © 2020 life michael Jump Start  The simples way to develop a decorator would be to develop a function that has one parameter to which a function is passed over.  Whenever our decorator is invoked (enough to have in our code @ourdecorator to invoke the decorator) the decorated function will be passed over to our decorator.
  • 5. © 2020 life michael Jump Start  The decorator function should include the definition of another function, the decorator function returns. That other inner function usually invokes the decorated function.  The function returned by our decorator will take the place of the decorated function. Every call to the decorated function in our code will be replaced by a call to the function returned by our decorator.
  • 6. © 2020 life michael Jump Start def uppercase(func): print("2") def inner(): print("4") data = func() return data.upper() return inner print("9") @uppercase def getGreeting(): print("13") return "good morning" print("16") print(getGreeting())
  • 7. © 2020 life michael Decorating Function with Parameters  In order to decorate a function with parameter(s) we just need make sure the function returned by the decorator has the same parameter(s) accordingly.
  • 8. © 2020 life michael Decorating Function with Parameters def uppercase(func): print("2") def inner(nickname): print("4") data = func(nickname) return data.upper() return inner print("9") @uppercase def getGreeting(nickname): print("13") return "good morning " + nickname print("16") print(getGreeting("dave"))
  • 9. © 2020 life michael Using a Class as Decorator  The decorator should be a callable object. It can be a function. I can also be a class we define together with the __init__ and the __call__.
  • 10. © 2020 life michael Using a Class as Decorator class uppercase: def __init__(self, f): self.f = f def __call__(self, nickname): return self.f(nickname).upper() @uppercase def greet(nickname): return "good morning " + nickname print(greet("danny"))
  • 11. © 2020 life michael Decorators Nesting  We can place together more than one decorator. Doing so, we should imagine the decorators execution one after the other in the order in which they are listed (top to bottom).  The output of each decorator execution is the input for the decorator above.
  • 12. © 2020 life michael Decorators Nesting def uppercase(func): def inner(nickname): data = func(nickname) return data.upper() return inner def stars(func): def inner(text): input = func(text) return "*** "+input+" ***" return inner @stars @uppercase def getGreeting(nickname): return "good morning " + nickname print(getGreeting("dave"))
  • 13. © 2020 life michael Class Decorators  We can develop a decorator for classes. The object that represents a class is also a factory function that is called whenever a new object is created. def bang(func): def inner(): print("bang!!!") ob = func() return ob return inner @bang class Rectangle(): pass ob1 = Rectangle() ob2 = Rectangle()
  • 14. © 2020 life michael Decorators with Arguments  We can develop a decorator that takes arguments when called. def bang(text): def f(func): def inner(): print(text) ob = func() return ob return inner return f @bang(text="Picaso") def Rectangle(): pass ob1 = Rectangle() ob2 = Rectangle()
  • 15. © 2020 life michael Stateful Decorators  We can develop a decorator that keeps tracking of a state by using attributes we add to the object that represents the decorator. def counter(text): if not hasattr(counter,"classes"): counter.classes = dict() if text not in counter.classes: counter.classes[text] = 0 def f(func): def inner(): counter.classes[text] = int(counter.classes[text]) + 1 ob = func() return ob return inner return f
  • 16. © 2020 life michael Stateful Decorators @counter("Rectangle") class Rectangle(): pass @counter("Circle") class Circle(): pass rec1 = Rectangle() rec2 = Rectangle() rec3 = Rectangle() circ1 = Circle() circ2 = Circle() print(counter.classes["Rectangle"]) print(counter.classes["Circle"])
  • 17. © 2020 life michael Real World Examples
  • 18. © 2020 life michael Measuring Execution Time  We can easily develop a decorator for the purpose of measuring the execution time of specific functions. import time def stopper(func): def inner(times): start = time.perf_counter() value = func(times) end = time.perf_counter() run = end - start print("running_time=",run) return value return inner @stopper def doSomething(times): total = 0 for i in range(times): total += i return total doSomething(99999)
  • 19. © 2020 life michael Debugging & Logging  We can easily develop a decorator that will track each and every execution of a specific function. def tinylog(func): def f(*args, **kwargs): args1 = [repr(a) for a in args] args2 = [repr(k)+":"+repr(v) for k, v in kwargs.items()] value = func(*args, **kwargs) print("calling ", func.__name__, " ", repr(args1), " ", repr(args2), " returns ", value) return value return f @tinylog def total(a,b): return a+b print(total(3,4)) print(total(5,5)) print(total(8,7))
  • 20. © 2020 life michael Libraries Development  We can easily create decorators for functions and classes as part of a library for other developers.  There are many libraries that employ the power of decorators in their service, including ORM libraries (e.g. PonyORM), Unit Testing libraries (e.g. Testify) and others.
  • 21. © 2020 life michael Caching Data  Assuming that we have a function that fetches data from the server we can develop a decorator that will provide us with an caching mechanism.
  • 22. © 2020 life michael Questions & Answers  Thanks for attending this meetup.