Pythonic way to save all form input to dict?

Hi all - I’ve answered my own question since starting to write this but thought I’d post it anyway in case the incantation was of any help/interest to others…

SITUATION

I had an input Form mainly with checkboxes and full English names e.g. self.delivery_status and wanted to get the ‘names’ as strings for each of them e.g. “delivery_status”. I needed this so I could update a dictionary something like this: {"delivery_status": False, "pickup_status": False}.

TARGET

I wanted to find a Pythonic way of getting this list of component ‘names’ (as strings, not objects) rather than typing them out manually and ending up with a hard-coded list of Keys that I’d have to remember to update if my Form ever changed in future.

SOLUTION

checkboxes = [x for x in dir(self) if type(getattr(self,x)) == CheckBox]

(Obviously you can adapt this to quickly get a list of any other component types).

nice - here’s some other pythonic approaches that are much the same:

checkboxes = [x for x in dir(self) if type(getattr(self,x)) is CheckBox]

or

checkboxes = [x for x in dir(self) if isinstance(getattr(self, x), CheckBox)]

and if you’re using it to update a dictionary where the keys match the names of the checkboxes you could do…

status_dict =  {"delivery_status": False, "pickup_status": False}
status_dict.update({status: getattr(self, status).checked for status in status_dict})

and you could set up the inital status_dict by doing

status_dict = {cb: False for cb in dir(self) if isinstance(getattr(self, cb), CheckBox)}

1 Like

YES! That’s exactly what I was trying to do, thanks Stu. Perfect! This is really question of learning Python rather than learning Anvil but I think Anvil’s an obvious use case for an elegant one-liner…

1 Like