I've got a collection of users with two types of IDs (a_id, b_id) where one is a positive integer and the other is a six-letter string. For my collection class, I'd like to be able to look up users using either type of ID.
Is there something wrong with using __contains__
and __getitem__
for either type of ID?
class UserList: def __init__(self, users_json): self.a_ids = {} self.b_ids = {} for user in users_json: a_id = user['a_id'] b_id = user['b_id'] self.a_ids[a_id] = user self.b_ids[b_id] = user def __contains__(self, some_id): return some_id in self.a_ids or some_id in self.b_ids def __getitem__(self, some_id): try: return self.a_ids[some_id] except KeyError: return self.b_ids[some_id]
Update: This is for Python 3.x, and there is no implementation of __setitem__
; updating users is handled in separate API functions.
__setitem__
? Are you using Python 3.3+? The answer to all of these could make a drastically different answer.\$\endgroup\$