Is this decorator typed correctly, given the current limits of mypy? I include example usage below:
import functools
from typing import TypeVar, Type, Any, cast
C = TypeVar('C', bound=Type[Any])
def singleton(cls: C) -> C:
"""Transforms a class into a Singleton (only one instance can exist)."""
@functools.wraps(cls)
def wrapper(*args: Any, **kwargs: Any) -> Any:
if not wrapper.instance: # type: ignore # https://github.com/python/mypy/issues/2087
wrapper.instance = cls(*args, **kwargs) # type: ignore # https://github.com/python/mypy/issues/2087
return wrapper.instance # type: ignore # https://github.com/python/mypy/issues/2087
wrapper.instance = None # type: ignore # https://github.com/python/mypy/issues/2087
return cast(C, wrapper)
@singleton
class Test:
pass
if __name__ == '__main__':
a = Test()
b = Test()
print(a is b)
I had to add type: ignore
on the lines where the instance
attribute appears because otherwise mypy would flag these errors:
error: "Callable[..., Any]" has no attribute "instance"