I make heavy use of assertions in many languages. A really easy way to get more context is to just dump out a map/dictionary of values. For example, in Python:
assert foo == bar, repr({
"error": "Foo and bar should not be equal",
"foo": foo,
"bar": bar,
})
It’s easy enough to wrap this into a function (although that may lose line number information, depending on the language), e.g.:
I do a similar thing in other languages by dumping out the context information as JSON. One thing to be careful about is whether that info itself will cause problems: huge values are annoying, but infinite/cyclic values may break the error message itself! Also in a lazy language we may have values in scope which haven’t yet been forced, and trying to write them out as JSON may trigger an error. I find it best to code defensively in these situations (assertions are useful precisely when we are wrong about what’s happening!), e.g. not including values which are only accessed after the assertion.
Cool to see the interview with Power Assert’s author. I always like seeing how people came up with their ideas and philosophies.
The content is good, but this kind of UI jitter is really distracting: https://gfycat.com/PotableSameGoldenmantledgroundsquirrel
Thanks for pointing that out. We just pushed up a fix, and the issue should hopefully be resolved now.
I make heavy use of assertions in many languages. A really easy way to get more context is to just dump out a map/dictionary of values. For example, in Python:
It’s easy enough to wrap this into a function (although that may lose line number information, depending on the language), e.g.:
I do a similar thing in other languages by dumping out the context information as JSON. One thing to be careful about is whether that info itself will cause problems: huge values are annoying, but infinite/cyclic values may break the error message itself! Also in a lazy language we may have values in scope which haven’t yet been forced, and trying to write them out as JSON may trigger an error. I find it best to code defensively in these situations (assertions are useful precisely when we are wrong about what’s happening!), e.g. not including values which are only accessed after the assertion.