4 ms·
It mentions in the PEP discussion that the {a, b} trick only works for string keys. So it isn't applicable in as many cases as the new operator.
by war1025 7y ago
It mentions in the PEP discussion that the {a, b} trick only works for string keys. So it isn't applicable in as many cases as the new operator.
- seemslegit 7y agodict(d1, **d2) only works with string keys {**d1,**d2} or dict({**d1,**d2}) works with all key types it seems
- uryga 7y agoactually, only dict(d1, **d2) has that problem. it works fine if you unpack into a dict literal: >>> d1 = {1: 'a'} >>> d2 = {2: 'b'} >>> {**d1, **d2} {1: 'a', 2: 'b'} iirc the pep mostly just says that it's suboptimal because it's syntactically heavy/noisy, non-obvious and can't be overloaded in dict subclasses --- i was curious why the two double-stars behave differently despite syntactic similarity. so i went and checked the bytecode, and it turns out they compile down to different opcodes! `{××d1, ××d2}` yields a BUILD_MAP_UNPACK, while `dict(d1, ××d2)` yields a CALL_FUNCTION_EX/CALL_FUNCTION_KW (depending on the CPython version)
- dahfizz 7y agoThis seems pretty straightforward. When doing `dict(d1, d2)` You are calling the dict function, and using the normal syntax for unpacking a dictionary into kwargs. In this case, the name for kwargs must be strings.
- uryga 7y agoyeah, that side of the (in)equation was pretty obvious, i was mostly interested in the `{...}` one. i admit that a bytecode listing probably isn't the best exposition, i just like digging into VM stuff :)