πŸ€” Do you ever write some Python 🐍, look at it, and get the feeling there MUST be a better ✨ way to do that..?

I get that ALL the time! πŸ˜…

That's why I started researching and writing articles to help me (and you!) write better code.

Here's all 28 of them (so far!) πŸ‘‡πŸ§΅
I have also been compiling all the articles into an eBook πŸ“–, that I am "selling" for free πŸ’Έ.

Why?

I decided to make it free because that's how I learned Python: from free books and articles, available online.

Here's the link to the free book:

gum.co/pydonts
01 - Pydon't disrespect the Zen of Python

If you type `import this` in a Python REPL, you will be presented with the Zen of Python, a document with some guidelines that you can follow when writing code.

It's not a religion!

Just some guidelines :)

mathspp.com/blog/pydonts/p…
02 – Unpacking with starred assignments

This article shows you how to use the star `*` in multiple assignments to extract portions of iterables that you may be interested in.

mathspp.com/blog/pydonts/u…
03 – EAFP and LBYL coding styles

In Python, we have `try: ... except: ...` blocks, and it is often considered idiomatic Python code to use them (EAFP) instead of using pre-emptive checks with `if` statements (LBYL).

Here's a look at these two styles:

mathspp.com/blog/pydonts/e…
04 – Assignment expressions and the walrus operator

The walrus operator `:=` was introduced in Python 3.8.

This article teaches you its behaviour and then presents some interesting use cases for it.

mathspp.com/blog/pydonts/a…
05 – `str` and `repr`

The two built-in functions `str` and `repr` are closely related, and sometimes people don't even know about `repr`!

Or they do know about `repr`, but have no idea what it's for!

This article takes care of that 😊

mathspp.com/blog/pydonts/s…
06 – Truthy, Falsy, and `bool`

This article goes deep into one of my favourite vanilla Python features: the Truthy and Falsy values of objects.

Knowing how to use this enables you to use some very idiomatic patterns.

mathspp.com/blog/pydonts/t…
07 – Watch our for recursion

As a mathematician, I find recursion very elegant.

Often, solutions to problems present themselves as recursive solutions.

However, there are some gotchas to using recursion in Python. That's what I cover in this article.

mathspp.com/blog/pydonts/w…
08 – Deep unpacking

This feature deals with the structure of things like lists and tuples, and allows for some really neat code.

This is also a feature you should know, in order to make the most of the `match` statement coming in Python 3.10!

mathspp.com/blog/pydonts/d…
09 – Chaining comparison operators

Another neat thing about Python that I haven't seen in many other languages (actually, off the top of my head, I can't recall _any_).

When doing some comparisons, you can actually chain them, here's how/when/why:

mathspp.com/blog/pydonts/c…
10 – Structural pattern matching tutorial

Here's most of what there is to know about the `match` statement that is coming to Python in version 3.10.

This article shows the syntax and some great use cases.

mathspp.com/blog/pydonts/s…
11 – Structural pattern matching anti-patterns

Even though `match` has great potential, I can foresee some people will go bananas and start using it everywhere.

This article covers some situations where `match` _could_ be used, but probably shouldn't:

mathspp.com/blog/pydonts/s…
12 – Zip up

Python's `for` loops are AMAZING.

Like, hands down, beautiful.

If you know what you are doing, `for` loops can be read as English sentences.

For that to happen, you must know about `zip`, one of my favourite built-in functions.

mathspp.com/blog/pydonts/z…
13 – Enumerate me

Along the same lines, `enumerate` is another fabulous built-in function that you will wish you had known from day 1.

Probably, one of the built-in functions I use the most in my Python code!

mathspp.com/blog/pydonts/e…
14 – Sequence indexing

This article sets up the stage for a 3-part "series" on slicing.

This article reintroduces indexing syntax and shows some diagrams to get you comfortable with negative indexing, a Python super power.

mathspp.com/blog/pydonts/s…
15 – Idiomatic sequence slicing

Part 1/3 introduces slicing syntax and draws parallels between slicing and indexing with a `for` loop.

It also introduces four idiomatic slicing patterns you should be comfortable with.

mathspp.com/blog/pydonts/i…
16 – Mastering sequence slicing

Part 2/3 covers more advanced stuff, like

- using negative steps;
- assigning directly to slices; and
- deleting slices.

mathspp.com/blog/pydonts/m…
17 – Inner workings of sequence slicing

In part 3/3 we look under the hood, and understand how Python slices objects.

We learn about the built-in `slice` and some dunder methods, like `__getitem__`.

We also see how to implement slicing for yourself.

mathspp.com/blog/pydonts/m…
18 – Boolean short-circuiting

Boolean short-circuiting allows you to write long(er) conditions where some parts may not even get evaluated.

This may sound weird, but has some powerful usages!

mathspp.com/blog/pydonts/b…
19 – The power of `reduce`

`reduce` used to be a built-in function, but was relegated to the module `functools` in Python 3.

What many fail to realise, is that `reduce` is what drives many built-ins like `sum`, `all`, `any`, `max`, and `min`.

mathspp.com/blog/pydonts/t…
20 – Usages of underscore

From making your numbers more readable, ...

to marking β€œmagic” methods and attributes, ...

to storing lost REPL values;

the underscore is a low-key character that sure is handy!

Here's everything I could find about it:

mathspp.com/blog/pydonts/u…
21 – `__name__` dunder attribute

The dunder attribute `__name__` often shows up in the form of

```
if __name__ == "__main__":
...
```

but there is more to it than you might know!

No worries, I did all the research, you can just read the findings:

mathspp.com/blog/pydonts/n…
22 – Does elegance matter?

Perhaps more on the philosophical side of things, I wonder whether elegance matters when writing computer programs...

And whether you like it or not, it sure does; in many ways:

mathspp.com/blog/pydonts/d…
23 – Bite-sized refactoring

If elegance matters, you need to know how to make your code more elegant.

That often comes through refactoring, because you won't write the best code ever on the first try.

Refactoring is hard work, but also fruitful work.

mathspp.com/blog/pydonts/b…
24 – Code style matters

Still along the lines of the importance of elegance, the style of your code is also relevant.

Some of it can be automated, though, so you don't have to lose your hair over the placement of all the commas, spaces, newlines, etc 😁

mathspp.com/blog/pydonts/c…
25 – Naming matters

Often dubbed as the hardest problem in programming, naming your variables, functions, etc, is HARD.

Like, VERY HARD.

I took a look at Python's conventions, dissected them, and sprinkled in some tips to make it easier on you 😊

mathspp.com/blog/pydonts/n…
26 – String `translate` and `maketrans` methods

Python's types come with many, many methods; often, we aren't even aware of all of them!

This article shines some light on two interesting string methods.

Sure, they're kind of niche, but still awesome!

mathspp.com/blog/pydonts/s…
27 – Boost your productivity with the REPL

One of the things I enjoy about Python is that I can just open the terminal, run `python`, and play with Python interactively!

Learning how to use the REPL properly will surely boost your Python productivity.

mathspp.com/blog/pydonts/b…
28 – `set` and `frozenset`

This article covers two built-in types that people are generally not aware of: the `set` and the `frozenset`.

I introduce you to them and take a look at their intended use cases, showing you where (frozen) sets really shine.

mathspp.com/blog/pydonts/s…
These are the 28 Pydon't articles I have published so far, and many more are on the way!

Give them a read, and let me know your feedback!

I want to hear your thoughts!

If you want to make sure you don't miss the next Pydon'ts, subscribe here:

mathspp.com/subscribe
That's it for this thread!

I hope you enjoyed it.

If you found value, consider following me (@mathsppblog) and retweet the beginning of the thread to make sure everyone gets a fair chance at writing their best Python 🐍 code yet!

β€’ β€’ β€’

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

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.

πŸ‘‡πŸ§΅ Image
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
9 Sep
Have you ever had a hard time debugging 🐞 a Python 🐍 script?

If you say you haven't, you're lying! πŸ˜†

Let me show you something that you're gonna love me for!

Run your script with the `-i` flag!

By doing so, you get a REPL when the script finishes, EVEN with errors πŸ’£

1/4
Let me show you an example.

Below is a piece of code I wrote in a script called `foo`.

If you look closely, you'll see I'm generating 100 random integers...

All of them between 0 and... 0! So I'll generate 100 zeroes (my bug).

Later, a 0/0 division will throw an error.

2/4
When I run the code with the `-i` flag, the terminal shows the error and immediately opens a REPL!

From within the REPL I can inspect my variables and figure out what went wrong!

Isn't this amazing ⁉

3/4
Read 5 tweets
8 Sep
Have you ever tried to optimise your Python 🐍 code, but weren't able to tell which alternative implementation was faster?

Let me teach you how to use the `timeit.timeit` method to measure execution time of small code snippets.

A thread πŸ‘‡πŸ§΅
If you have a snippet of code you want to time, you can use the command line to measure its execution time.

For example, how long does it take for Python 🐍 to add up the first 10,000 integers?

Using the command `python -m timeit`, I get that it takes 189 microseconds.
The execution of `python -m timeit` reports some more info:

β€œ2000 loops, best of 5: ...”

I'll explain what that means, but first let me show you how to use `timeit` in your code.

(Oh, btw, there's a MUCH better way to add consecutive integers! πŸ‘‡)
Read 23 tweets
8 Sep
Did you know that Python 🐍 supports keyword argument unpacking?

What's that?

If you have a function that accepts a series of arguments: `arg1`, `arg2`, ...

And if you have a dictionary with keys named `arg1`, `arg2`, ...

Then you can use the dict's values as arguments: Image
The `**` in front of `kwargs` does the unpacking in the function call.

`my_func(kwargs)` – this calls `my_func` with a single argument, the `kwargs` variable (a dictionary in the image above)

...
`my_func(**kwargs)` – this calls `my_func` with one named argument for each (key, value) pair in the dictionary.

E.g., in the above,

`my_func(**kwargs)` unpacks to `my_func(a=73, b="hey!", c=(1, 10))`.
Read 4 tweets
7 Sep
@svpino Hey Santiago! I'd just like to clarify something for the readers of this thread:

The formula

P(A or B or C) = P(A) + P(B) + P(C) - P(A and B and C) is NOT β€Ό true in general.

The result works here because the events are mutually exclusive and P(A and B and C) = 0

1/
@svpino But the actual general formula is

P(A or B or C) = P(A) + P(B) + P(C) - P(A and B) - P(B and C) - P(A and C) + P(A and B and C)

You can read up on the inclusion-exclusion principle, which explains this: πŸ”— en.wikipedia.org/wiki/Inclusion…

This can also be explained visually:

2/
@svpino Checking the overlaps below πŸ‘‡

The ellipsis (representing the events) can overlap all over the place, and we CANNOT overcount the overlaps!

So, we need to remove the pairwise overlaps:

A and B
A and C
B and C

But when we do that, we over-subtract the final intersection,

3/
Read 4 tweets
2 Sep
Have you ever seen anything like this in Python 🐍 loops??

I just saw this being used for the first time, ever, and I decided to figure out what the heck this was...

And so here goes the explanation πŸ‘‡πŸ§΅

1/
Foreword:

Python has many amazing capabilities to deal with `for` loops, among which you can count the `zip` and `enumerate` built-ins.

This little thread assumes you are familiar with both.

Read these if you need:
πŸ”—Β mathspp.com/blog/pydonts/e…
πŸ”—Β mathspp.com/blog/pydonts/z…

2/
When using `zip` and `enumerate` in your `for` loops, something you do often is to unpack the values you are iterating over.

Unpacking, in and out of itself, is an amazing feature of Python, and you can read about it in the linked article if needed.

mathspp.com/blog/pydonts/d…

3/
Read 10 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!

:(