Matt Harrison Profile picture
Apr 27 13 tweets 5 min read Twitter logo Read on Twitter
I often teach about Decorators in Python.

Many know how to use them, but few can write them.

These are tricky because nested functions make our brains hurt.

Here are some hints for grokking them.

1/ Image
In short, decorators allow you to inject orthogonal behavior before or after a function is executed.

But my favorite decorator definition is related to the construction and will help you easily create them: A callable that takes a callable and returns a callable.

2/
What do I mean by "orthogonal"?

A function should do one thing. If you want to add caching or logging, it really isn't related to the function (and could be applied to multiple functions). It is "orthogonal" behavior.

3/
What is "callable that takes a callable and returns a callable"?

Remember this. It will make decorators easy. When we execute a function in Python we "call" it.

So, you could also say: A decorator is a function that takes a function and returns a function.

4/ Image
(Although Python has other *callables* like methods, classes, lambdas, or instances with .__call__. You can implement decorators with these, but we will ignore them here.)

5/
The simplest decorator is one I call the *identity* decorator. It is a function that accepts a function and returns a function:

6/ Image
We can decorate a function by redefining it or using Python's syntactic sugar: "@". These two snippets are equivalent:

7/ Image
If your brain is fine with the identity decorator, let's just expand it and write the decorator like this. (Remember "a function that takes a function and returns a function".)

8/ Image
When we decorate with this new code, the call to "add" actually calls "wrapper" which calls add ("func") when it executes.

The key point is that we can inject logic before "func" and after. (See blue and orange in the image.)

9/ Image
To make a caching decorator, insert the logic to look for a prior answer in #before, and stick the result of the function in the cache in #after.

Here is an example that would cache in Redis:

gist.github.com/mminer/34d4746…

10/
So back to the first image.

Here's your template for decorators.

The final bit with
@wraps
(func) updates .__name__ and .__doc__ so that code completion works in editors and you can pull up documentation.

11/ Image
I have a book, Intermediate Python Programming, covering decorators and other fun constructs like generators, comprehensions, and functional programming.

store.metasnake.com/intermediate-p…
That's a wrap!

If you enjoyed this thread:

1. Follow me @__mharrison__ for more of these
2. RT the tweet below to share this thread with your audience

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Matt Harrison

Matt Harrison Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

More from @__mharrison__

Apr 27
Here's what I'm running on my @elgato Stream Deck.

Media controls, pomodoro timer, local time, Zoom mute, and (two buttons) for Zoom Exit (need to hit Return after hitting the Run button 🤷‍♀️) Image
World times (useful for client work and meetings).

Application launchers. (Some of these should be launched at startup on Windows... 🤔Looking at you TPFanControl and PowerToys.) Image
Tool to configure Stream Deck and brightness controls. Image
Read 4 tweets
Apr 20
Inspired by @svpino and @dvassallo, I want to be more deliberate with my tweeting. To start that off, I wanted to understand (quantitatively) how I tweet.
And that is the essence of "Applied Pandas: Twitter Analytics". I show how to access your Twitter data, set up an environment, and perform exploratory data analysis on it. 📉
We clean up the code, do time series analysis, merge data into it, visualize it, and wrap up with demoing applying machine learning to the data to get further insight. 🤯
Read 6 tweets
Apr 20
Suggestions for writing better Python code:

📝Use an Editor that gives feedback
✅Format consistently
🧪Test your code
🦆Use type hints
📚Learn Python idioms
Editors like @pycharm, @code can give you quick insight into coding issues.

I have @emacs configured to do similar. Image
Using a tool like Black can eliminate many qualms and issues during code reviews that just waste time.

(Sadly, I don't like how black works with Pandas chained code. 😢🐼)

github.com/psf/black
Read 8 tweets
Apr 18
One of the most important choices you have in life is your work. 👷

How do you decide where to work?

What to do?

How do you get your first job?

When to start looking for a new job?

🧵
Most people want a job that has both satisfying work and good perks...
You might think these jobs are unobtainable and only what you read about but they are not accessible to you. But over my career, I've seen otherwise.
Read 8 tweets
Apr 4
A thread about pandas... (The library not the animal)

🐼🧵
I like to describe pandas:

⋅ Like Excel

⋅ Like SQL

Things that you would do with Excel or SQL, you can program in pandas
It is a Python library, so it is good to understand these parts of the Python language:

* Syntax (index vs invocation vs attribute access, slicing)

* Functions

* Lambdas

* List comprehensions
Read 7 tweets
Apr 3
Inspired by @svpino and @dvassallo, I want to be more deliberate with my tweeting. To start that off, I wanted to understand (quantitatively) how I tweet.
And that is the essence of "Applied Pandas: Twitter Analytics". I show how to access your Twitter data, set up an environment, and perform exploratory data analysis on it. 📉
We clean up the code, do time series analysis, merge data into it, visualize it, and wrap up with demoing applying machine learning to the data to get further insight. 🤯
Read 6 tweets

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us on Twitter!

:(