简体   繁体   中英

How to generate a return type-hint from self?

I'd like to generate the return type hint from a string which is defined on __init__() within the class:

class MyItem:
    return_type: str = None

    def __init__(self, return_type: str):
        self.return_type = return_type

    def get_item() -> self.return_type:   # <--- Is something like that possible?
        return ...
    

Any idea how to achieve that?

No. I don't think so. Type hints are used by type checkers, IDEs, linters, etc... . Because your classes aren't instantiated until runtime, this won't work.

Consider the following code:

class MyItem:
    return_type: str = None

    def __init__(self, return_type: str):
        self.return_type = return_type

    def get_item() -> self.return_type:   # <--- Is something like that possible?
        return ...

a = MyItem("Str")
b = a 
b.return_type = "int" 

The linter would have to run the constructor for a , note that b is a , and then update the return type where b 's return type is updated. I can't see a way for the linter or IDE to check return types without running the code first, and we know that type hints have no effect at runtime. This is a cool idea though. This type of behaviour reminds me of sealed classes in kotlin.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM