I have a long list of groups in json and I want a little utility:
def verify_group(group_id):
group_ids = set()
for grp in groups:
group_ids.add(grp.get("pk"))
return group_id in group_ids
The obvious approach is to load the set outside the function, or otherwise declare a global -- but let's assume I don't want a global variable.
In statically typed languages I can say that the set is static and, I believe that will accomplish my aim. How would one do something similar in python? That is : the first call initializes the set, group_ids, subsequent calls use the set initialized in the first call.
BTW, when I use the profilestats package to profile this little code snippet, I see these frightening results:
ncalls tottime percall cumtime percall filename:lineno(function)
833 0.613 0.001 1.059 0.001 verify_users_groups.py:25(verify_group)
2558976 0.253 0.000 0.253 0.000 {method 'get' of 'dict' objects}
2558976 0.193 0.000 0.193 0.000 {method 'add' of 'set' objects}
I tried adding functools.lru_cache -- but that type of optimization doesn't address my present question -- how can I load the set group_ids once inside a def block?
Thank you for your time.