Skip to content

Commit

Permalink
fix scope init
Browse files Browse the repository at this point in the history
  • Loading branch information
Ed-XCF committed Jun 27, 2022
1 parent 4abd559 commit 56ddb19
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions scoped_singleton.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,19 @@ def __setitem__(self, key, value):
class ThreadLocalRegistry(Registry):
def __init__(self):
self.scope = threading.local()
self.scope.registry = WeakValueDictionary()
self.registry_factory = WeakValueDictionary

def __contains__(self, key):
return key in self.scope.registry
return key in getattr(self.scope, "registry", {})

def __getitem__(self, item):
return self.scope.registry[item]
return getattr(self.scope, "registry", {}).get(item)

def __setitem__(self, key, value):
self.scope.registry[key] = value
old_registry = getattr(self.scope, "registry", None)
new_registry = old_registry.copy() if old_registry else self.registry_factory()
new_registry[key] = value
self.scope.registry = new_registry


class ContextVarRegistry(Registry):
Expand All @@ -56,7 +59,9 @@ def __getitem__(self, item):
return self.scope.get()[item]

def __setitem__(self, key, value):
self.scope.get()[key] = value
new_registry = self.scope.get().copy()
new_registry[key] = value
self.scope.set(new_registry)


def scoped_singleton(registry_klass: Type[Registry], cls):
Expand Down

0 comments on commit 56ddb19

Please sign in to comment.