3 ms·
> In 2023, it's rude to return dictionaries. :) Why do you say that? I think you were partially kidding, but also half serious. What’s the issue with returnin
by proamdev123 3y ago
> In 2023, it's rude to return dictionaries. :)
Why do you say that?
I think you were partially kidding, but also half serious. What’s the issue with returning dictionaries, and why should we be returning dataclasses instead?
Asking for my own learning.
- sanderjd 3y agoData classes are "self-documenting" with respect to the "keys" you can expect to be present. Relatedly, they enable meaningful type hints: def some_method(input: Dict[str, int]): ... You can just as easily call `some_method({"foo": 1})` as `some_method({"bar": 2})`. vs. def some_method(input: MyDataClassWithFoo): ... Now you can't pass a dict where the key is "bar" and presumably get a KeyError when it tries to look up a "foo" key, you can only pass a MyDataClassWithFoo.
- gen220 3y agoRegarding the 2023 part, it's because dataclasses in Python are pretty fully-featured and part of the stdlib, so building rich data structures is quick, ergonomic, and helps remove/centralize boilerplate and parsing (aka validating, see https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/ https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-va...). Regarding rude, yea it was a bit tongue-in-cheek (I would never hold a grudge against somebody for returning a dict). You should generally define an interface for your function that's as precise as its logic allows for. `Dict` is as good as `Any`: it doesn't tell you very much about what the function internally expects. The sibling comment to mine does a good job going through this.