興味深い問題です。次のようなことを試してみます。
from abc import ABCMeta
class Registry(object):
def __init__(self):
self._proxies = {}
self._classes = {}
def resolve(self, name):
try:
return self._classes[name]
except KeyError:
raise KeyError('Cannot resolve "%s".'
' Class not registered yet.' % name)
def __getitem__(self, name):
"""Return a proxy class bound to `name`."""
if name not in self._proxies:
self._proxies[name] = make_proxy(lambda: self.resolve(name))
return self._proxies[name]
def __setitem__(self, name, val):
"""Store a class for `name`."""
self._classes[name] = val
def make_proxy(resolve):
"""
Return a proxy class.
:param resolve: a function that returns the actual class
"""
class ProxyMeta(ABCMeta):
"""
Custom meta class based on ABCMeta that forwards various checks
to the resolved class.
"""
def __eq__(self, y):
return resolve() == y
def __repr__(self):
return repr(resolve())
def __str__(self):
return str(resolve())
class Proxy(object):
"""
The actual proxy class.
"""
__metaclass__ = ProxyMeta
def __new__(cls, *args, **kwargs):
"""Calling this class returns an instance of the resolved class."""
return resolve()(*args, **kwargs)
@classmethod
def __subclasshook__(cls, subclass):
"""issubclass() overwrite."""
return issubclass(resolve(), subclass)
return Proxy
>>> registry = Registry()
>>> List = registry['list']
>>> List
KeyError: 'Cannot resolve "list". Class not registered yet.'
>>> registry['list'] = list
>>> List
<type 'list'>
>>> issubclass(List, List)
True
>>> issubclass(list, List)
True
>>> List == list
True
>>> List()
[]
>>> registry['list'] = tuple
>>> List()
()