Skip to content

Instantly share code, notes, and snippets.

@koenvo
Forked from dtheodor/goal_dict.py
Last active January 4, 2016 16:59
Show Gist options
  • Save koenvo/8650725 to your computer and use it in GitHub Desktop.
Save koenvo/8650725 to your computer and use it in GitHub Desktop.
GaTransactionConf = namedtuple("GaTransactionConf", ["sku", "name", "category"])
class GaTransactionsDict(dict):
def __getitem__(self, key):
if isinstance(key, GaTransactionConf):
updated = False
for mapping in self.keys():
if cmp_ga_conf(key, mapping):
key = mapping #update the key
updated = True
break # should we break??
if not updated:
raise KeyError("not found")
return dict.__getitem__(self, key)
def cmp_ga_conf(record, goal_mapping):
if ((goal_mapping.sku is None or record.sku in goal_mapping.sku) and
(goal_mapping.name is None or record.name in goal_mapping.name) and
(goal_mapping.category is None or record.category in goal_mapping.category)):
return True
else:
return False
a = GaTransactionConf(sku=(1,2), name=(3,4), category=None)
goal_dict = GaTransactionsDict({a:1})
print goal_dict
b = GaTransactionConf(sku=(1,2), name=(3,4), category=None)
assert goal_dict[b] is goal_dict[a]
c = GaTransactionConf(sku=1,name=3,category=None)
assert goal_dict[c] == goal_dict[a]
@dtheodor
Copy link

The return dict.__getitem__(self, key) will raise the KeyError for us. Just need to break (and whether we break or not is irrelevant... if we have 2 mappings that match the goal, the way we have it working now this is a user mistake)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment