We are adding type hints to our code base and there's one specific case where I don't know how to do proper type hinting. We have a function that will create an instance of a specific class if it didn't yet exist. The class of which it creates an object is defined in the function itself to make it a Singleton. An example of such a function is given in the following piece of code:
__GREETER = None
def get_greeter():
global __GREETER
class Greeter:
def greet_user(name: str):
print(f'Hello {name}')
if not __GREETER:
__GREETER = Greeter()
return __GREETER
I was now wondering how we can add a type hint for the return type of the get_greeter() function. Can I just use get_greeter() -> 'Greeter'
or should I do something different?
Note that there are indeed cleaner ways to define singletons since python 3 but refactoring that is something on the backlog.
I would suggest a slight refactoring of your code, to make it a more generic approach. You can make a singleton pattern applicable, even if you expose your class. For eg. see below.
class Greeter:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(Greeter, cls).__new__(cls)
return cls._instance
def greet_user(name: str):
print(f'Hello {name}')
You can re-write your Greeter class, which makes sure its a singleton. Now for backward compatibility, keep the method you have as it is.
def get_greeter() -> Greeter:
return Greeter()
It creates only one instance ever. And your hinting is also achieved.
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.