KeyErrors in data bindings are silenced

I’ve recently noticed that KeyErrors in component data bindings are silenced, with evaluation quietly aborted at the point where the error gets raised. This is the case for at least Label and RichText components and does not extend to other exceptions like ValueError.

Is this by design? I got caught out by this last week, thinking that my code had run without issues after a refactor, not realizing that a KeyError had stopped the data binding code from completing successfully.

See this app for a reproducible example:

2 Likes

Hi @br4m.vandekerckhove,

That’s right - this behaviour is by design, and KeyErrors in Data Binding expressions are ignored. The reason is that frequently a Form will be bound to (for example) an empty dictionary, and this needs to work. The Data Bindings docs have been updated to make this clearer!

1 Like

Is this a recent change or has it always been like this? I’ve been using code like self.item.get('key') in data bindings when I want to silence KeyErrors.

@hugetim, it’s been going on since I started developing with Anvil, years ago. Lots of things happen at Form construction time, which would be fatal, if those errors weren’t ignored.

@meredydd, this change to the Data Bindings docs is a model of clarity! I especially like Why are Data Bindings useful? Context and rationale are key to understanding virtually every topic I can imagine, and with non-trivial topics, like data binding, even seasoned developers need all the help we can get. Thanks a million!

3 Likes