Show more

@peterdrake @chris @s_gruppetta right!

I usually explain to my students by noting that __iadd__ stands for in-place addition and in-place operations are intended to mutate the original object when possible.

Though += and friends are most often used on strings and numbers, which are immutable so we don't see that behavior most of the time...

I do wonder whether it might have been more sensible to design Python to never mutate with augmented assignments, even on mutable objects.

@peterdrake @chris As @s_gruppetta said, it's all about how += works on lists.

+= on mutable objects is a combination of __iadd__ and =,

The __iadd__ call succeeds but the assignment fails

Interestingly += on tuples doesn't work this way! The += operator falls back to __add__ followed by an assignment on immutable objects.

So while

a += b

Is the same as

a = a + b

With a tuple or a string.

Those two lines aren't the same on a list!

This oddity is in the docs too: docs.python.org/3.5/faq/progra

Still one of the oldest #Python oddities I've ever seen 🐍🤔

>>> a = ([],)
>>> a[0] += ["what"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a
(['what'],)

Note that an exception was raised but the operation also worked! 😳 #pythonoddity

This evening I've played a wee bit more with my #Textual Mandelbrot Set plotter. Some tweaks mean that it's now easier to move/zoom and home in on interesting features (zoom wasn't well done before).

Standard disclaimers apply: this isn't done as an efficient Textual app; it's written to really test the edges. Even so, it's performing really well!

#Python

youtube.com/watch?v=_-aJwLqQDF

I should do an #introduction

My name is Will McGugan, I am a software developer that works mainly with #Python

You may know me from the #Python community as the creator of Rich.

I'm also the CEO of Textualize, a startup dedicate to improving terminals. We're currently building #Textual, a Python #TUI framework.

Not sure whether you’re only meant to get a single shot at an , but I’ll extend on mine a bit now that I’m starting to find my feet here

My main focus is on communicating about , specifically . That includes teaching!

However, my first career was as a physicist


After studying and and then getting my PhD in Physics from Imperial College, London, I went down the normal route of a few postdocs, an academic fellowship, and then a lectureship.

Most of my science work centred around novel retinal imaging technology with the primary aim of early disease diagnosis, plus a bit more about the optics of the eye.

I learnt to code as part of my PhD work and then relied on programming (mostly MATLAB, at the time, before the Python-era) for all of my research work, from simulation and modelling, to running the lab experiments, to analysing the data.


When I left academia, I decided to focus on teaching programming to both children and adults.

I spend a lot of time creating learning content, including The Python Coding Book and regular articles on the blog.

I also run codetoday which runs live lessons for children from age 7 to learn coding in Python (only Python, no kids-platforms. Yes, starting from age 7, you’d be surprised how well they pick the basics up)


I’ll be sharing bits on content regularly here too, typically aimed at intermediate learners (including those aiming to move from beginners to intermediate), including steering towards scientific programming and related fields.

OK, I’ve abused ’s longer character limit too much, so I’d better stop!

Show thread

question: Is a private toot the same as followers-only?

It’s nice to be able to post using markdown - it will also make posting code more natural

print("Hello, Mastodon!")

Although I’ve noticed that on the iOS app I’m using (the official one), markdown is not rendered. It is on the web platform.

Not sure about other apps…

PS: I believe this is not a feature on all servers…

Using Python to create a solar system

If anyone is looking for a fun exercise to flex their fingers…

Using just gravitational attraction between bodies, you can create your own 2D solar system with as many stars and planets as you want. Here’s a binary star system with some relatively stable planets

Here’s the article, including a detailed step-by-step tutorial, if you want to read more: Simulating Orbiting Planets in a Solar System Using Python

…and there’s also a 3D version (next post)

We'll return to the Python functions series tomorrow!

/11

Show thread

They're easy to miss and ignore. But if you've read documentation, you will definitely have seen a * or a / in many function signatures

Now, when you see them next, you'll know perfectly well what they are and what they do

/10

Show thread

Or maybe you use Matplotlib? Here's `plt.scatter()`

Wait for it

scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)

Did you spot the lone * ?

/9

Show thread

Maybe you use NumPy a lot? Positional-only and keyword-only arguments appear very often in the NumPy codebase

Here's just one example, NumPy's `mean()` method:

a.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)

/8

Show thread

Let's check:

>>> "hello".replace("l", '-')
'he--o'

>>> "hello".replace(old="l", new='-')
Traceback (most recent call last):
...
TypeError: str.replace() takes no keyword arguments

/7

Show thread

How about `str.replace()`? You've used that too?

Here's the signature:

replace(self, old, new, count=-1, /)

`old`, `new`, and `count` are all positional-only

/6

Show thread

`key` and `reverse` are keyword-only in `list.sort()`

/5

Show thread

>>> numbers = [4, 6, 7, 2]
>>> numbers.sort(reverse=True)
>>> numbers
[7, 6, 4, 2]

All fine here. But try to use a positional argument instead:

>>> numbers.sort(True)
Traceback (most recent call last):
...
TypeError: sort() takes no positional arguments

/4

Show thread

Have you ever used `list.sort()` with the `key` or `reverse` parameters?

I bet you have!

Here's the signature for `list.sort()`

sort(self, /, *, key=None, reverse=False)

/3

Show thread

Why do we need them? Are they even ever used?

I bet you've seen them many times and ignored them. I'll go further and bet you've used them, too, without knowing

/2

Show thread
Show more
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.