Last active
December 2, 2024 22:37
-
-
Save angstwad/94d11c71e3837fa0e9a56ecd069bf3b0 to your computer and use it in GitHub Desktop.
Simple, thread-safe singleton mixin class for Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SingletonMixin: | |
""" Threading safe singleton mixin class. Will run __init__ on subclasses for every | |
invocation, so check self._initialized from __init__ to get around this if not desired. | |
Use: | |
class MyClass(SingletonMixin): | |
def __init__(self): | |
if not self._initialized: | |
# initialize here | |
self.foo = 'bar' | |
# when done, set initialized to True | |
self._initialized = True | |
""" | |
_instances: dict[type, Any] = {} | |
_lock = threading.Lock() | |
_initialized: bool | |
def __new__(cls): | |
with SingletonMixin._lock: | |
if cls not in SingletonMixin._instances: | |
# Create instance | |
instance = super().__new__(cls) | |
SingletonMixin._instances[cls] = instance | |
instance._initialized = False | |
# Return existing instance | |
return SingletonMixin._instances[cls] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Copyright 2024 Paul Durivage <[email protected]> | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment