Skip to content

ding.utils.design_helper

ding.utils.design_helper

SingletonMetaclass

Bases: ABCMeta

Overview

Returns the given type instance in input class

Interfaces: __call__

__call__(*args, **kwargs)

Overview

Returns the given type instance in input class

Full Source Code

../ding/utils/design_helper.py

1from abc import ABCMeta 2 3 4# ABCMeta is a subclass of type, extending ABCMeta makes this metaclass is compatible with some classes 5# which extends ABC 6class SingletonMetaclass(ABCMeta): 7 """ 8 Overview: 9 Returns the given type instance in input class 10 Interfaces: 11 ``__call__`` 12 """ 13 instances = {} 14 15 def __call__(cls: type, *args, **kwargs) -> object: 16 """ 17 Overview: 18 Returns the given type instance in input class 19 """ 20 21 if cls not in SingletonMetaclass.instances: 22 SingletonMetaclass.instances[cls] = super(SingletonMetaclass, cls).__call__(*args, **kwargs) 23 cls.instance = SingletonMetaclass.instances[cls] 24 return SingletonMetaclass.instances[cls]