@mratsim's solution is very good for prototyping, and probably what you want. 
The Json module is the recommended way to get python dictionary behavior in 
Nim. It's the generally recommended way to transition Python programmers to Nim 
:-P

> if one couldn't come up with a Nim implementation of the exact behavior of 
> python dictionaries?

But, a native Python dictionary is probably never going to be put in the std 
library. Nim is a **statically typed language** , and this is dynamic behavior! 
You are setting the types of the dictionary at runtime. This is against the 
philosophy of statically typed languages like Nim.

Dynamic types like this have a cost. It's still much faster than Python, but it 
isn't free, and you loose most of the Nim type safety.

Variant types like in your initial post is the most idiomatic Nim, type safe 
way to do it. In fact, this is how Nim does it for the compiler: 
[https://nim-lang.org/docs/manual.html#types-object-variants](https://nim-lang.org/docs/manual.html#types-object-variants)

Unfortunately, as @doofenstein pointed out, you have hit a limitation of 
variant types in the current Nim. Either every variant that shares a field must 
be grouped together, or each variant must have a different field name. This is 
slightly inconvenient, I agree, and the proposed fix has stalled unfortunately 
(bigger fish to fry in the compiler).

The advantage of variant types is that the compiler can warn you at compile 
time if you attempt to access a field on an Action that doesn't exist for that 
action type. You won't get that with a Dictionary. You (or your user) will get 
a run time error instead (this is the point of static types).

One strategy may be to use the Json dictionary while you are prototyping, then 
once you have a better idea of what fields you need on each Action type, swap 
it out for a Variant type. Personally, I prefer to just use Variant types up 
front, because it lets me more clearly design my data types, and lets the 
compiler help me (by yelling at me) if I forgot a field somewhere. 

Reply via email to