←back to thread

191 points jwilk | 3 comments | | HN request time: 0.714s | source
Show context
sundarurfriend ◴[] No.46230418[source]
Can someone ELI5 the core difference between this and named tuples, for someone who is not deep into Python? ChatGPT's answer boiled down to: unordered (this) vs ordered (NTs), "arbitrary keys, decided at runtime" vs "fixed set of fields decided at definition time" (can't an NT's keys also be interpolated from runtime values?), and a different API (`.keys()`, `.items()`), etc (I'm just giving this as context btw, no idea if there's inaccuracies in these).

So could this also have been approached from the other side, as in making unordered NamedTuples with support for the Mapping API? The line between dictionaries and named tuples and structs (across various languages) has always seemed a bit blurry to me, so I'm trying to get a better picture of it all through this.

replies(5): >>46230459 #>>46230674 #>>46230747 #>>46230783 #>>46237202 #
willvarfar ◴[] No.46230783[source]
The values in tuples cannot change. The values that keys point to in a frozen dict can?

But yeah I'd be in favour of something that looked a lot like a named tuple but with mutable values and supporting [name] access too. And of course some nice syntactic sugar rather like dicts and sets have with curly brackets today.

replies(1): >>46230838 #
pansa2 ◴[] No.46230838[source]
> The values in tuples cannot change. The values that keys point to in a frozen dict can?

The entries of a tuple cannot be assigned to, but the values can be mutated. The same is true for a `frozendict` (according to the PEP they don't support `__setitem__`, but "values can be mutable").

replies(1): >>46231249 #
1. vscode-rest ◴[] No.46231249[source]
Tuple entries must be hashable, which (as far as standard library is concerned) means immutable.
replies(1): >>46231273 #
2. pansa2 ◴[] No.46231273[source]

  >>> hash([1, 2])
  TypeError: unhashable type: 'list'

  >>> t = ([1, 2], [3, 4])
  >>> print(t)
  ([1, 2], [3, 4])
replies(1): >>46231393 #
3. vscode-rest ◴[] No.46231393[source]
Ah. Of course… that’s how the workaround to use tuples as frozen dicts can work in the first place. Slow morning for me!