0
ctx['location_ids'] = vals['location_ids'] 

I have a large function so I will not post it here, but the problem is when vals['location_ids'] have values as integer everything works smooth, but sometimes there are no values in vals['location_ids'] so it is False, and when it is False I get error.

ctx['location_ids'] = vals['location_ids']
TypeError: 'bool' object has no attribute '__getitem__'

how can I avoid it, maybe add hasattr?

Chaban33
  • 1,362
  • 11
  • 38
  • Check if it's `False` before using it...? – Aran-Fey Oct 10 '18 at 07:27
  • Yes, you can use `hasattr()`, but really you should probably do something else than assigning it a boolean value; keep things as uniform types (so if you expect to index `vals`, it should always be dictionary-like). – alkasm Oct 10 '18 at 07:31
  • @AlexanderReynolds How would you use `hasattr` to check if a variable is `False`? – Aran-Fey Oct 10 '18 at 07:31
  • @Aran-Fey `hasattr(vals, '__getitem__')`...? – alkasm Oct 10 '18 at 07:32
  • Ugh... Yeah, please don't do that. There's like half a dozen better ways to do it. – Aran-Fey Oct 10 '18 at 07:32
  • Yeah, not great. Wasn't suggesting they do that, just that they could. But not much worse than checking if something that should be a dictionary is a boolean IMO, and at least it follows duck-typing principles of Python...well, I suppose better would be `except KeyError` flow. Either way we can agree all of these solutions are bandaids, and the best action would be to change the code up the chain if possible. – alkasm Oct 10 '18 at 07:34

1 Answers1

1

you should try to check first it's dictionary

if isinstance(vals, dict):
   ctx['location_ids'] = vals.get('location_ids', None)
Nordle
  • 2,915
  • 3
  • 16
  • 34
aman kumar
  • 3,086
  • 1
  • 17
  • 24