@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: https://docs.python.org/3.5/faq/programming.html#faq-augmented-assignment-tuple-error
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!
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 #introduction, 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 #programming, specifically #Python. That includes teaching!
However, my first career was as a physicist
After studying #Maths and #Physics 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 #QOTO’s longer character limit too much, so I’d better stop!
#newbie 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…
The 3D version uses #matplotlib for the animation
Here’s the article: Simulating a 3D Solar System In Python Using Matplotlib
If anyone is looking for a fun exercise to flex their #Python #coding 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
#Python #simulation #animation
…and there’s also a 3D version (next post)
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
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
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
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
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
>>> 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
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
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
• Rethinking how to teach programming – I prefer the friendly, relaxed approach when communicating about Python programming
• I write about Python on The Python Coding Book blog and on Real Python
• Former Physicist
• Expect posts on scientific and numerical programming –> NumPy, Matplotlib and friends!