3 ms·
that's all cool and fine, but can you unpack named tuple or struct (data class)? In Julia one of my favorite quality of life improvement in the 1.7: https://git
by moelf 4y ago
that's all cool and fine, but can you unpack named tuple or struct (data class)? In Julia one of my favorite quality of life improvement in the 1.7: https://github.com/JuliaLang/julia/pull/39285 https://github.com/JuliaLang/julia/pull/39285
Example:
julia> X = (this = 3, that = 5)
(this = 3, that = 5)
julia> this
ERROR: UndefVarError: this not defined
julia> (;that, this) = X;
julia> this
3
julia> that
5
this works with structs as well (in fact anything with getproperty() defined, so like dataframe column too)
- jwilk 4y agoIf you don't mind questionable hacks, you can implement it in Python by abusing the import system: https://stackoverflow.com/a/69860087 https://stackoverflow.com/a/69860087
- kzrdude 4y agonamedtuple yes, it's a tuple so can be unpacked (by position) and dataclasses can not be unpacked. But with the new pattern matching, you can "unpack" dataclass objects that way! https://peps.python.org/pep-0636/ https://peps.python.org/pep-0636/
- jwilk 4y agoJavaScript has it too; it's called "object destructuring": https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#object_destructuring https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- est 4y agolooks can be done with some weird locals().__setitem__ hack .
- rsfern 4y agoThat’s cool that this is in Julia Base! Do you know how it compares to Unpack.jl? I love this feature because you can do partial unpacking by name https://github.com/mauro3/Unpack.jl https://github.com/mauro3/Unpack.jl
- moelf 4y agoUnpack.jl happened before this got added to Julia Base. You can always partially unpack, just only put what you need on the LHS
- girzel 4y agoI've enjoyed using types.SimpleNamespace: >>> from types import SimpleNamespace >>> d = {"one":1, "two":2} >>> ns = SimpleNamespace(**d) >>> ns.two 2 I consider it a bonus that the dict keys are grouped as attributes on an object :)
- raymondh 4y agoAs I teacher, types.SimpleNamespace is wonderful for helping people bridge between their understanding of dicts (a fundamental) to classes/instances (a little less fundamental). However, I almost never use SimpleNamespace in real code. Dicts offer extra capabilities: get, pop, popitem, clear, copy, keys, values, items). Classes/instances offer extra capabilities: unique and shared keys in distinct namespaces, instances knowing their own type, and an elegant transformation of method calls ``a.m(b, c)`` --> ``type(a).m(a, b, c)``. Dataclasses and named tuples have their advantages as well. In practice, it is almost never that case that SimpleNamespace beats one of the alternatives.