5 ms·
> "Preserving the order of kwargs in a function" "What are you trying to achieve?"
by smegel 10y ago
> "Preserving the order of kwargs in a function"
"What are you trying to achieve?"
- omginternets 10y agoIt's a side-effect.
- masklinn 10y agoThough it's something which has been requested in the past. Also preserving the ordering of class definitions.
- thomasahle 10y agoThere is a motivation segment in the PEP: https://www.python.org/dev/peps/pep-0468/#motivation https://www.python.org/dev/peps/pep-0468/#motivation I don't quite get it though.
- dalke 10y agoSuppose you want to make something like an XML generator helper function: def start(tag_, **kwargs): write("<" + escape(tag_)) if kwargs: for k, v in kwargs.item(): write(" " + escape(k) + "=" + quote_escape(v)) write(">") (Apply hand-wavying to get the correct code.) This might be called as: start("abc", x="1.0", y="2.0") but generate the output <abc y="2.0" x="1.0"> when you want it to be: <abc x="1.0" y="2.0"> The output order depends on the Python hash implementation, which (in modern Pythons) is randomly selected during startup. For an API which preserves order, you must currently either pass in the pairs in iterable order, like: start("abc", (("x", "1.0"), ("y", "2.0"))) or switch the API to pass in a dictionary-like object instead of kwargs, then switch to an OrderedDict (which must also be initialized with pairs in iterable order). In 3.6, there's no need for that -- kwargs will preserve the keyword parameter order.
- kzrdude 10y agoThis is why it will be defacto stabilized quickly (because it's so useful). I'm sure the python developers have considered that, since they explicitly chose to preserve order instead of other small non-order preserving optimizations that could have been done with the new representation.
- thomasahle 10y agostart("abc", x="1.0", y="2.0") <abc y="2.0" x="1.0"> Ok, I can imagine people wanting this. Especially people coming form Javascript. However `<abc y="2.0" x="1.0">` and `<abc x="1.0" y="2.0">` are semantically equivalent in XML, aren't they?
- masklinn 10y agoXML itself doesn't no, humans may, and some crappy crummy tools sadly do as well[0]. Round-tripping ordering is also convenient for automated processing tools as well (e.g. add/remove parameters without introducing extraneous unnecessary changes) [0] some also do care about namespace aliases/prefixes, which is a bit of a shock the first time they choke on your perfectly valid and namespaced XML.
- dalke 10y agoThey are equivalent. That doesn't mean that all tools will use XML semantics to test for equivalence. A testing tool might require that the output is byte-for-byte equivalent to a known good output. Python's pseudorandomly determined hash function won't preserve that order across multiple runs.