Say, I have a function that should do some internal stuff and display the provided text:
def display_text(text: str):
...
print(text)
There's also a class with a convert() method:
class String:
def __init__(self, string: str):
self.string = string
def convert(self):
return self.string
Now, can you type hint text argument in display_text with String, but if the provided parameter will be str, call convert and assign the returned value to text? Like that:
def display_text(text: String):
...
print(text)
It should be done without any additional code in a display_text function, just with type hinting. I've seen that in some libs but couldn't figure out how does it work.
I tried searching through some libraries' (e.g. discord.py converters) code, searching similar questions on StackOverflow, only found out about typing.Protocol but still no idea how this conversion is done.
No, not just with type hinting, since type annotations are absolutely inert at runtime and do nothing (and with
from __future__ import annotations, they're not even evaluated). If this is a trick question and that "in adisplay_textfunction" was the catch, then yes, you could @decorate your functions (or decorate a class holding them, or use a metaclass) to wrap functions using type annotations to cast arguments if needed.An example of such a decorator:
This prints out