5 ms·
I've been toying around with Python 3 and using it for most of my personal/hack projects, but I somehow missed the unpacking improvements: https://www.python.or
by re 9y ago
I've been toying around with Python 3 and using it for most of my personal/hack projects, but I somehow missed the unpacking improvements: https://www.python.org/dev/peps/pep-0448/ https://www.python.org/dev/peps/pep-0448/
In particular, being able to create an updated copy of a dict with a single expression is pretty cool:
return {**old, 'foo': 'bar'}
# Old way
new = old.copy
new['foo'] = ['bar']
return new
- miracle2k 9y agoMy mind is blown. Ever since JavaScript added this, I've been wanting it in Python... and somehow it was there all along. It works for lists too! [*a, *b, *c]
- agumonkey 9y agobear in mind that most things javascript got recently are old. literals, closure syntax, destruct, spread .. (lisp, scheme of course, but yeah python took it a while back too) this is all very very old but now ECMAxxxx is bringing it to the mainstream.
- orf 9y agoAnd the performance is pretty much the same, just a lot nicer syntax In [1]: x = {1:2, 3:4} In [2]: %timeit x[3] = 5 48.6 ns ± 1.18 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) In [3]: %timeit y = x.copy(); y[3] = 5 189 ns ± 3.23 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) In [4]: %timeit {**x, 3: 5} 182 ns ± 3.3 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) Edit: It also seems to be pretty constant time if you're just merging: In [16]: %timeit {**x, **y, **z} 180 ns ± 1.29 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) In [17]: %timeit {**x, **y, **z, 3: 5} 278 ns ± 18.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [19]: dis.dis(lambda: {**x, **y, **z, 3: 5}) 0 LOAD_GLOBAL 0 (x) 2 LOAD_GLOBAL 1 (y) 4 LOAD_GLOBAL 2 (z) 6 LOAD_CONST 1 (3) 8 LOAD_CONST 2 (5) 10 BUILD_MAP 1 12 BUILD_MAP_UNPACK 4 14 RETURN_VALUE In [20]: dis.dis(lambda: {**x, **y, **z}) 0 LOAD_GLOBAL 0 (x) 2 LOAD_GLOBAL 1 (y) 4 LOAD_GLOBAL 2 (z) 6 BUILD_MAP_UNPACK 3 8 RETURN_VALUE
- est 9y agoreturn {**old, 'foo': 'bar'} # Old way return dict(old, foo='bar') Not much difference if you ask me.
- delaaxe 9y agoI've been practicing Python for a while and didn't even know about this. In my code style, I try to completely avoid the "dict" keyword and exclusively use dict literal notation.
- orf 9y agoIt's twice as slow, doesn't work with more than one dictionary, you can't easily control the merge prescience and you can't (easily) use expressions/variables in the keys: {**x, 'fo'+'o': 'bar', **y}
- vonseel 9y agoThis is a lot like JavaScript :)
- amyjess 9y agoIt also allows for unioning two dicts together: baz = {**foo, **bar}
- deleted 9y ago[deleted]
- sametmax 9y agoAlso: a, *b, c = range(10)