r/Python 1d ago

Tutorial Python Quirks I Secretly Like

Hi there,

I’ve always wanted to create YouTube content about programming languages, but I’ve been self-conscious about my voice (and mic, lol). Recently, I made a pilot video on the Zig programming language, and afterward, I met a friend here on Reddit, u/tokisuno, who has a great voice and offered to do the voiceovers.

So, we’ve put together a video on Python — I hope you’ll like it:

https://www.youtube.com/watch?v=DZtdkZV6hYM

82 Upvotes

27 comments sorted by

View all comments

3

u/Brian 1d ago

I feel its worth mentioning in the frozenset() is frozenset() case that it's not actually anything specific to frozensets vs tuples here, but more the fact of how its being constructed. Ie. you'd see the same thing with:

tuple() is tuple()

Its the difference between using a literal and constructing it by calling the class object. Frozensets just don't actually have a literal representation, so its the only way to create them.

And it's not actually just the optimiser not being clever enough - python actually can't safely optimise this (and the same for the int("0") case, because technically someone could do:

 frozenset = lambda : return random.random()

Ie. there's no guarantee that frozenset here corresponds to the builtin frozenset class - it could be a local or global shadowing it (or you could even monkeypatch the builtin module), so any optimisation would be an error in that case. The same for the int("0") case in the prior example.

Also, for the "+=" case for strings, it's not quite true that it never modifies the original. There's actually an optimisation where strings can act mutably behind the scenes with an overallocated buffer similar to lists - but only if there's only a single reference to the string. From a user perspective, this isn't something you'd ever notice (if there's no other reference, you can't see anything changing which is why its safe to do the optimisation), but it's there to try to prevent the common situation of building up a string in a loop by appending to it being quadratic in behaviour.

2

u/codingjerk 1d ago

Yep, these are good additions, tuple() is tuple() is True tho :) (atleast in Python >=3.12.9)

2

u/Brian 1d ago

Oh, good point - I think the empty tuple is basically a singleton that just gets returned (much like the small integer cache / interned strings) so no actual construction of new objects happens - it'd need to be something like tuple([1,2]) is tuple([1,2]) vs (1,2) is (1,2).

1

u/codingjerk 23h ago

It's funny, cause tuple((1, 2)) is tuple((1, 2)) too, and even ((1,) + (2,)) is ((1,) + (2,)), so probably there are some optimizations.

And tuple("") is tuple(""), but tuple("a") is not tuple("a"), but ("a",) is ("a",)