3 ms·
The annoyance of dataclasses, of course, is that they interact very awkwardly with immutability, which much of the Python ecosystem mandates (due to lacking val
by o11c 2y ago
The annoyance of dataclasses, of course, is that they interact very awkwardly with immutability, which much of the Python ecosystem mandates (due to lacking value semantics).
But yes, they're still the least-bad choice.
- the__alchemist 2y agoValid. One of my biggest (Perhaps my #1) fault with python is sloppy mutability and pass-by-value/reference rules.
- Spivak 2y agoIs there a situation where Python ever passes by value? Like you can sort of pretend for primitive types but I can't think of case where it's actually value.
- o11c 2y agoNon-CPython implementations may pass by value as an optimization for certain immutable builtin types. This is visible to code using `is`. (It's surprisingly difficult to implement a rigorous way to detect this vs compile-time constant evaluation though; note that identical objects of certain types are pooled already when generating/loading bytecode files. I don't think any current implementation is smart enough to optimize the following though) $ python3 -c 'o = object(); print(id(o) is id(o))' False $ pypy3 -c 'o = object(); print(id(o) is id(o))' True $ jython -c 'o = object(); print(id(o) is id(o))' True
- cwalv 2y agoAre you saying `o` is passed by value? I think this behavior is due to the return from `id()` being interned, or not. `id(o) == id(o)` will be true in all cases
- o11c 2y agoI mean that the `id` function returns by value. It's not interning since that explicitly refers to something allocated, which isn't the case here.
- ericvsmith 2y agoThis is incorrect. The returned integer is a regular Python object, not some "unboxed" integer value.
- ericvsmith 2y agoWhat you're seeing here is an optimization about integers, not about pass by value. CPython only does this for small integers: $ python -c "print(int('3') is int('3'))" True $ python -c "print(int('300') is int('300'))" False Other implementations make different choices.
- nomel 2y ago> is that they interact very awkwardly with immutability How so? Tuples are awkward with immutability, if you put mutable things inside them.
- o11c 2y agoBy default, dataclasses can't be used as keys in a `dict`. You have to either use `frozen` (in which case the generated `__init__` becomes an abomination) or use `unsafe_hash` (in which case you have no guardrails). In languages with value semantics, nothing about this problem even makes sense, since obviously a dict's key is taken by value if it needs to be stored. -- Tuple behavior is sensible if you are familiar with discussion of reference semantics (though not as much as if you also support value semantics). Still, at least we aren't Javascript where the question of using composite keys is answered with "screw you".
- porridgeraisin 2y agoHaha obj[JSON.stringify(x)] = y * Ducks *
- o11c 2y agox = [Symbol('geese')]