1
class Foo:
    method_type: type

    def method(self) -> ???:
        # code



# Example use:


class FooStr(Foo):
    method_type = str

foo_str = FooStr().method() # should be str according to vscode's intellisense


class FooInt(Foo):
    method_type = int

foo_int = FooInt().method() # similarly, this should be int

Note that simply replacing the ??? with method_type doesn't work as far as I've tested it.

How would I go about doing this?

1 Answer 1

2

A class attribute is a runtime value and Python doesn't really support types dependent on values. Python also doesn't have type members. So in conclusion, no this isn't possible. You'd need to use a generic

T = TypeVar("T")

class Foo(Generic[T]):
    def method(self) -> T:
        ...

class FooStr(Foo[str]):
    ...

class FooInt(Foo[int]):
    ...

which is similar, if not quite the same.

If you want to know more about the difference, here's a discussion about it in Scala.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.