Have you heard that Python 🐍 3.10 will be released soon?

Are you ready for when it drops πŸ’£πŸ”₯?

Python 3.10 will ship with the new ✨ match statement, and I created a cheatsheet just for that.

This is also a thread πŸ‘‡πŸ§΅ that breaks it down and explains everything:
The cheatsheet is free and teaches you 12+ things about the new `match` statement.

From the basics, to object destructuring, to wildcards, among other things.

Get it from the link πŸ‘‡, and keep reading below to learn all about the `match` statement.

mathspp.gumroad.com/l/cheatsheet_m…
In its most basic form, a `match` statement kind of resembles an `if` statement.

That's what most of the β€œswitch” or β€œmatch” statements in other languages do: a series of `if` / `elif` / `else` statements.

Even a basic `case` is powerful: use `|` to separate multiple options. Image
In Python, the `case` statement can be followed by an `if` statement.

This `if` statement can be used to add more restrictions on top of what the `case` catches.

In the `factorial` example below, we use it to make sure we only compute the factorial of positive numbers. Image
But... The `match` statement has a greater purpose!

The `match` statement was born to MATCH STRUCTURE of objects.

For example, a colour can be thought of as a name, plus the RGB values, plus an alpha channel for transparency.

How can we shape things into that structure? Image
The code above is doing PLENTY of things!

In such a little amount of code!

It accepts a `colour`, and tries its best to put it into the (name, (r, g, b, a)) format of the `return` statement.

In order to do so, it will give default values to missing pieces of information.
For example, the first `case` statement deals with this scenario:

We only receive RGB values.

If we only get RGB values, we create the default colour name (an empty string) and the default transparency value (0).

Here are some example calls: Image
Another cool thing is that you can give names to sub-patterns.

This is useful, for example, when you expect part of the structure to always remain the same...

... but you need to deal with a portion that changes: Image
But there is MORE!

The `match` statement knows how to do β€œobject destructuring”.

This means that the `match` statement can match objects depending on the values of their attributes!

Isn't that insane?!

For example, imagine you have a 2D point: Image
We can create a `case` statement that only matches points with specific `x` and `y` values.

Or with a specific `x` value and a generic `y` value.

Or the other way around.

Here are some examples: Image
Now, if you are ANYTHING like me...

You are lazy!

That's fine, programmers should be β€œlazy smart”.

Typing `x=` and `y=` in all the `case`s is boring and error-prone.

That's why the Python 🐍 Gods invented `__match_args__`:

Use it and say goodbye to `x=` and `y=` everywhere! Image
This was object destructuring done with custom classes...

But it can also be done with built-in types!

And when that is the case, it can act as a basic form of type validation!

Here is the colour example from before, but now ensuring everything has the correct type: Image
If we run the code above, we prevent all sorts of trouble if the things aren't what they should be!

Below, we trigger the `ValueError` by trying to use all sorts of funky stuff instead of the expected data types.

(Sure, maybe we could be lenient about the 26.0 πŸ˜‚) Image
After knowing all about object destructuring, I think it's cool to talk about wildcards.

There are two wildcards: `*` and `**`.

`*` is to be used with iterators (like lists and tuples).

It's also related to the `*args` idiom and unpacking with assignments: Image
The `**` wildcard is for dicts.

But first, here's something that might throw you off:

⚠ When a `case` statement includes specific keys (or key/value pairs), it doesn't try to check if that's the _whole_ dictionary.

It only checks if that portion is inside the given dict. Image
So, with that out of the way, it is safe to tell you that `**` matches an arbitrary portion of a dictionary.

Of course, that portion may or may not be empty.

(Much like the `*` wildcard can match an empty iterator.) Image
So, there's a nice combo you can make here, if you use the `**` wildcard and the `if` statements inside the `case` statements.

What's that?

You can write a neat `case` that checks if a given dictionary has the exact structure you are interested in: Image
This was a breakdown of the cheatsheet you saw in the beginning, which you can get for free πŸ‘‡

mathspp.gumroad.com/l/cheatsheet_m…
The cheatsheet, in turn, was a summary of my most popular blog article: πŸ”— mathspp.com/blog/pydonts/s…

If you want to learn more about the `match` statement":

I have a great article explaining when the `match` statement ISN'T the right tool for the job: πŸ”— mathspp.com/blog/pydonts/s…
That's it for now!

Do you want to level up your Python 🐍 game?

Want to get awesome Python 🐍 knowledge and content daily?

Then follow @mathsppblog because that is exactly what I do here on Twitter.

Also, if you found value in this thread, show your love πŸ’™ and retweet it 😊
Here's a TL;DR

1. `match` declares what object we are looking at;
2. `case` defines the cases we want to handle;
3. `|` separates multiple options;
4. use `if`s after `case`s to refine conditions;
5. use `_` to match any object at all (kind of like an `else`);
6. object destructuring works on custom classes;
7. object destructuring gives access to objects' attributes;
8. __match_args__ allows to remove boilerplate from `case`s;
9. object destructuring on built-ins works like basic type validation;
10. sub-patterns can be named;
11. use `*` with iters to match arbitrary sections;
12. `case` with dict don't check full structure;
13. `case` with dict can check just key or key/value pairs.
14. use `**` to match arbitrary portion of dict; and
15. use `**` with `if` to enforce specific dict structure.

Bye πŸ‘‹

β€’ β€’ β€’

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

Keep Current with Rodrigo πŸπŸ“

Rodrigo πŸπŸ“ 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 @mathsppblog

28 Sep
πŸ€” If you are learning Python 🐍, I want to do an experiment:

Here's a thread πŸ‘‡πŸ§΅ teaching you conditional expressions.

BUT, I will teach you with NO words 😢

I will only show code snippets and examples.

Check the thread out carefully πŸ” and then give me your feedback!
By the way, if you want to learn something from this thread...

I'm not going to lie, you'll have to focus πŸ”.

Also, what's the rationale for this crazy πŸ€ͺ thread?

By reading code and examples, you see first-hand how the feature is used and where it comes in handy.

Let's go:
Read 17 tweets
25 Sep
What's the BEST way to learn Python 🐍?

I've been writing Python for 10 years and taught 100s of people.

Here is a FAQ with actionable advice πŸ‘‡πŸ§΅

But everyone is different, so share your thoughts as well πŸ‘‡πŸ’¬ to help as many as possible!
🐍 β€œHow do I start learning Python?”

Well, I think the answer to this question greatly depends on whether you have (considerable) programming experience with another language or not.

That's because β€œlearning Python” can mean ”learn the syntax of the language”, but...
... it can also mean ”learn how to think like a programmer”.

And, in my opinion, this is something very fundamental that you have to understand!

Being a programmer is also about having that programmer mindset.

Worry not, you can learn it 😊
Read 35 tweets
24 Sep
Do you want to master Python 🐍 list comprehensions?

Do you want to become more proficient working with lists in Python 🐍?

If you answered with β€œyes”, then here's a cheatsheet of mine to help you out.

This is also a thread πŸ‘‡πŸ§΅ that breaks it down and explains everything:
First off, here is the anatomy of a list comprehension.

There's 4 parts to a list comp:
1. enclosing brackets to create the list [];
2. expression that transforms your data;
3. `for` iteration over the initial data;
4. (optional!) condition to filter some data.
Do list comprehensions look confusing?

Maybe.

But that's because you didn't realise that list comprehensions have equivalent `for` loops!

The coloured boxes below show the equivalent bits in the list comp and in the `for` loop:
Read 19 tweets
23 Sep
Do you know what the Python 🐍 `type` is?

But do you _really_ know what it is?

Here is a valuable thread that will give you insights into what `type` is and does.

Let's go πŸ‘‡πŸ§΅
What does `type` do?

You might say that `type` takes an object and returns the type of the argument.

Here are some examples:
Fine, so `type` is a function!

Or is it..?

Take a look at the example above.

`sum` is a built-in function and `type(sum)` returned β€œbuilt-in function or method”.

So, logically, if `type` is a (built-in) function, the type of `type` should give the same thing:
Read 14 tweets
20 Sep
Are you a master of Python 🐍 sequence slicing?

Here is a short thread 🧡 covering four idiomatic slicing patterns that you could get used to.

These four patterns are great because they have a clear interpretation of what they do.

Here we go πŸ‘‡πŸ§΅
🐍 s[n:]

If `n β‰₯ 0`, then `s[n:]` means

πŸ‘‰ β€œSkip the first `n` elements.”

⚠ If `n` is 0, then we skip 0 elements, which is another way of saying we get all of them.
That's the same as `s[:]`.
🐍 s[-n:]

If `n > 0`, then `s[-n:]` means

πŸ‘‰ β€œThe last `n` elements.”

⚠ -0 and 0 are the same, so `s[-0:]` gets all the sequence, like above.
Read 10 tweets
18 Sep
Are you as curious (and nerdy πŸ€“) as I am? πŸ€”

If you are, you are going to love what I'm about to show you 🀯

Let's build a Python 🐍 quine: a program that prints itself!

This thread walks you through the process of building the quine you can see here.

πŸ‘‡πŸ§΅
If we want a program that _prints_ itself, we need to start with a print statement:

```
print()
```

When we run this program, a single newline gets printed as output.

But we want a program that prints itself, right?

So let's try putting the program in the `print`.
For that, we try opening " inside the `print` and we start typing the program, itself, inside the string:

```
print("print()")
```

This outputs

```
print()
```

But now our program grew, so we need to keep up with it inside the string.
Read 11 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

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

Donate via Paypal Become our Patreon

Thank you for your support!

Follow Us on Twitter!

:(