I'm creating a singleton decorator for tests, but when I ask if an object is of instance of the original class it returns false.
In the example I'm decorating a counter class to create a singleton, so every time if I get the value it returns the next number no matter what instance of the object calls it. the code pretty much works but the function isinstance seems to break, I tried using functools.update_wrapper but I don't know if I can get isinstance function to recognize Singleton as Counter (in the following code) as long as when I ask for Counter the code actually returns Singleton.
def singleton(Class):
class Singleton:
__instance = None
def __new__(cls):
if not Singleton.__instance:
Singleton.__instance = Class()
return Singleton.__instance
#update_wrapper(Singleton, Class,
# assigned=('__module__', '__name__', '__qualname__', '__doc__', '__annotation__'),
# updated=()) #doesn't seems to work
return Singleton
@singleton
class Counter:
def __init__(self):
self.__value = -1
self.__limit = 6
@property
def value(self):
self.__value = (self.__value + 1) % self.limit
return self.__value
@property
def limit(self):
return self.__limit
@limit.setter
def limit(self, value):
if not isinstance(value, int):
raise ValueError('value must be an int.')
self.__limit = value
def reset(self):
self.__value = -1
def __iter__(self):
for _ in range(self.limit):
yield self.value
def __enter__(self):
return self
def __exit__(self,a,b,c):
pass
counter = Counter()
counter.limit = 7
counter.reset()
[counter.value for _ in range(2)]
with Counter() as cnt:
print([cnt.value for _ in range(10)]) #1
print([counter.value for _ in range(5)]) #2
print([val for val in Counter()]) #3
print(Counter) #4
print(type(counter)) #5
print(isinstance(counter, Counter)) #6
output:
#1 - [2, 3, 4, 5, 6, 0, 1, 2, 3, 4]
#2 - [5, 6, 0, 1, 2]
#3 - [3, 4, 5, 6, 0, 1, 2]
#4 - <class '__main__.singleton.<locals>.Singleton'>
#5 - <class '__main__.Counter'>
#6 - False
(with the update wrapper uncommented)
#1 - [2, 3, 4, 5, 6, 0, 1, 2, 3, 4]
#2 - [5, 6, 0, 1, 2]
#3 - [3, 4, 5, 6, 0, 1, 2]
#4 - <class '__main__.Counter'>
#5 - <class '__main__.Counter'>
#6 - False
You can use the singleton
class decorator in the Python Decorator Library .
It works because it modifies the existing class (replaces the __new__()
method) instead of replacing it with a completely separate class as is being done in the code in your question.
import functools
# from https://wiki.python.org/moin/PythonDecoratorLibrary#Singleton
def singleton(cls):
''' Use class as singleton. '''
cls.__new_original__ = cls.__new__
@functools.wraps(cls.__new__)
def singleton_new(cls, *args, **kw):
it = cls.__dict__.get('__it__')
if it is not None:
return it
cls.__it__ = it = cls.__new_original__(cls, *args, **kw)
it.__init_original__(*args, **kw)
return it
cls.__new__ = singleton_new
cls.__init_original__ = cls.__init__
cls.__init__ = object.__init__
return cls
With it, I get the following output (note the last line):
[2, 3, 4, 5, 6, 0, 1, 2, 3, 4]
[5, 6, 0, 1, 2]
[3, 4, 5, 6, 0, 1, 2]
<class '__main__.Counter'>
<class '__main__.Counter'>
True
Not better than the above, but slightly simpler and easier to remember if you ever need to do this from memory at a later point:
def singleton(Class, *initargs, **initkwargs):
__instance = Class(*initargs, **initkwargs)
Class.__new__ = lambda *args, **kwargs: __instance
Class.__init__ = lambda *args, **kwargs: None
return Class
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.