SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler 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.

Mais conteúdo relacionado

Mais procurados

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
Robert Davis
 
intro_to_python_20150825
intro_to_python_20150825intro_to_python_20150825
intro_to_python_20150825
Shung-Hsi Yu
 
Java căn bản - Chapter10
Java căn bản - Chapter10Java căn bản - Chapter10
Java căn bản - Chapter10
Vince Vo
 

Mais procurados (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
 

Semelhante a The Power of Decorators in Python [Meetup]

Python decorators
Python decoratorsPython decorators
Python decorators
Alex Su
 
Monads in python
Monads in pythonMonads in python
Monads in python
eldariof
 
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
 

Semelhante a 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
 

Mais de Haim Michael

Mais de 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)
 

Último

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 

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.