From 0f89ff4d6321036d6667bf4f33e6a7c256556a5e Mon Sep 17 00:00:00 2001 From: Dhruvan Ganesh Date: Wed, 10 Aug 2016 15:41:51 +0530 Subject: [PATCH] implemented Py2 & Py3 compatible Singleton --- nhentai/downloader.py | 8 ++------ nhentai/utils.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 6 deletions(-) create mode 100644 nhentai/utils.py diff --git a/nhentai/downloader.py b/nhentai/downloader.py index d15c26d..8916fb2 100644 --- a/nhentai/downloader.py +++ b/nhentai/downloader.py @@ -6,14 +6,10 @@ from urlparse import urlparse from logger import logger from parser import request +from nhentai.utils import Singleton -class Downloader(object): - _instance = None - def __new__(cls, *args, **kwargs): - if not cls._instance: - cls._instance = super(Downloader, cls).__new__(cls, *args, **kwargs) - return cls._instance +class Downloader(Singleton): def __init__(self, path='', thread=1, timeout=30): if not isinstance(thread, (int, )) or thread < 1 or thread > 10: diff --git a/nhentai/utils.py b/nhentai/utils.py new file mode 100644 index 0000000..dfbc21d --- /dev/null +++ b/nhentai/utils.py @@ -0,0 +1,10 @@ +# coding: utf-8 +class _Singleton(type): + """ A metaclass that creates a Singleton base class when called. """ + _instances = {} + def __call__(cls, *args, **kwargs): + if cls not in cls._instances: + cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs) + return cls._instances[cls] + +class Singleton(_Singleton('SingletonMeta', (object,), {})): pass \ No newline at end of file