Subscription
0
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning

Product type Book
Published in Dec 2015
Publisher Packt
ISBN-13 9781783551712
Pages 442 pages
Edition 1st Edition
Languages
Concepts
Author (1):
Mr. Fabrizio Romano

Learning Python
Credits
Acknowledgements
www.PacktPub.com
Preface
1. Introduction and First Steps – Take a Deep Breath 2. Built-in Data Types 3. Iterating and Making Decisions 4. Functions, the Building Blocks of Code 5. Saving Time and Memory 6. Advanced Concepts – OOP, Decorators, and Iterators 7. Testing, Profiling, and Dealing with Exceptions 8. The Edges – GUIs and Scripts 9. Data Science 10. Web Development Done Right 11. Debugging and Troubleshooting 12. Summing Up – A Complete Example Index

## Decorators

In the previous chapter, I measured the execution time of various expressions. If you recall, I had to initialize a variable to the start time, and subtract it from the current time after execution in order to calculate the elapsed time. I also printed it on the console after each measurement. That was very tedious.

Every time you find yourself repeating things, an alarm bell should go off. Can you put that code in a function and avoid repetition? The answer most of the time is yes, so let's look at an example.

`decorators/time.measure.start.py`

```from time import sleep, time

def f():
sleep(.3)

def g():
sleep(.5)

t = time()
f()
print('f took: ', time() - t)  # f took: 0.3003859519958496

t = time()
g()
print('g took:', time() - t)  # g took: 0.5005719661712646```

In the preceding code, I defined two functions, `f` and `g`, which do nothing but sleep (by 0.3 and 0.5 seconds respectively). I used the `sleep` function to suspend the execution for the desired amount of time. I also highlighted...

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