Don't let dicts spoil your code
roman.pt
Don't let dicts spoil your code
1–10 of 121 posts
Re: Don't let dicts spoil your code
#2I generally support this. When dealing with API endpoints especially I like to wrap them in a class that ends up being. I also like having nested data structures as their own class sometimes too. Depends on complexity & need of course.
class GetThingResult
def initialize(json)
@json = json
end
# single thing
def thing_id
@json.dig('wrapper', 'metadata', 'id')
end
# multiple things
def history
@json['history'].map { |h| ThingHistory.new(h) }
end
... two dozen more things
endRe: Don't let dicts spoil your code
#3I think one really nice thing about Python is duck typing. Your interfaces are rarely asking for a dict as much as they’re asking for a dict-like. It’s pretty great how often you can worry about this kind of problem at the appropriate time (now, later, never) without much pain.
There’s useful ideas in this post but I’d be careful not to throw the baby out with the bath water. Dicts are right there. There’s dict literals and dict comprehensions. Reach for more specific dict-likes when it really matters.
Re: Don't let dicts spoil your code
#4Debatable. Here's a counter-point:
https://www.youtube.com/watch?v=aSEQfqNYNAc
But ok, it's less bad in Python since objects are dicts anyway and you don't need getters.
Re: Don't let dicts spoil your code
#5Seems like the issue is less using dicts than not treating external APIs as input that needs to be sanitized.
Re: Don't let dicts spoil your code
#6Less important in Elixir (where they are "maps") due to the immutable nature of them as well as the Struct type which is a structured map.
Re: Don't let dicts spoil your code
#7Seems like the issue is less using dicts than not treating external APIs as input that needs to be sanitized.
Agreed. If you sanitize/allowlist API data you should not have issues with dicts.
Re: Don't let dicts spoil your code
#8Lists and sets suffer the same drawbacks. If the advice is to not use any of the batteries included if the language, why are we using Python?
If you want an immutable mapping, why not use an enum?
Re: Don't let dicts spoil your code
#9For better or for worse, Python doesn't do typing well. I don't disagree that I prefer well defined types, but if that is your desire then I think Python is perhaps not the correct choice of language.
Re: Don't let dicts spoil your code
#10FYI, posted in 2020, updated in 2021.