matt harrison Profile picture
Feb 8 12 tweets 5 min read
Last week I taught a course that covered 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/
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/
(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/
We can decorate a function by redefining it or using Python's syntactic sugar: "@". These two snippets are equivalent:

7/
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/
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/
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/
If you enjoyed this, follow me for more Python insights.

I have a book, Intermediate Python Programming, covering decorators and other fun constructs like generators, comprehensions, and functional programming. It is 30% off today.

store.metasnake.com/intermediate-p…

END!

• • •

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__

Oct 28, 2021
Let's explore the "any" and "all" built-in functions in Python.

A 🧵
First of all, I'll teach you how to fish in Python before giving you the fish. 🐟🎣

The built-in "help" function will give you documentation in Python. Make liberal use of it and reach out to it before ceding control to a search engine.
These are "aggregation" or "reducing" functions. They take a sequence and collapse it to a single value.

"any" returns if any value was truthy.
"all" returns if all values were truthy.

Most examples look like this:
Read 8 tweets
Oct 27, 2021
Here's a crazy piece of Python code (from @driscollis) illustrating how to calculate prime numbers below 1000 in a "functional" style.

How would I write this?

🧵

Functional programming like this can be great for minimizing lines of code. But it is also great for making your brain spin. Here is how I would initially write this (if I were fancy, I would use the Sieve of Eratosthenes):
Can we collapse this into fewer lines of code? Certainly, (the functional style already showed that) we can. One thing to realize is that lines 3-6 can be replaced with an any call:
Read 8 tweets
Oct 26, 2021
I'm frequently asked: Is it easy to get a tech job?

Probably not. It will require a degree (or a lot of hard work). People who say otherwise are probably selling you something.

1/
I've taught thousands of people Python over the years. Some pick it up quickly, others really struggle. That is why Universities have "weeder" courses. To sift out the strugglers.

2/
Does that mean you can't self-learn? No, but it will take a lot more work than just sitting back and watching YouTube.

3/
Read 5 tweets
Jul 15, 2021
A lot of people ask about my teleprompter...

Here is a 🧵 🠷 Image
When #Covid19 kicked in, I lost a good deal of training business that didn't want to move from live to virtual training.

Rather than give up. I doubled down...
I invested in equipment and software so I could deliver the best virtual training possible @__metasnake__ 🐍📈
Read 11 tweets
May 18, 2021
This tweet obviously resonates with many.

I often get asked about debugging when teaching a course...

A 🧵

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.

-Kernighan's Law

🤯
When I teach programming, I emphasize that to me, the most important part is that the code is "readable."

You write code (once or twice), but it is read all the time. Optimize for what happens a lot.

Not:

😦 Brevity
😦 Cleverness
😦 Using all of the features
Read 13 tweets
Mar 17, 2021
I'm teaching a Fundamentals of Python class this week.

We talked about tuples, and there was some confusion as to their existence.

Certainly, you could live in a world without them, but...

🧵
First of all ... pronunciation.

You can say "two-pull" or "tuh-pull" (both are valid).
A big confusion is when to use a list or tuple?

My basic rule of thumb:

If you have items of the same type and care about the order or re-arranging it, you want a list.
Read 9 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!

:(