4

I have a method that returns dynamic type based on the class I pass in:

def foo(cls):
    return cls()

How can I setup typing for this function?

1 Answer 1

2

After reading this article https://blog.yuo.be/2016/05/08/python-3-5-getting-to-grips-with-type-hints/, I found solution myself:

from typing import TypeVar, Type

class A:

    def a(self):
        return 'a'


class B(A):

    def b(self):
        return 'b'


T = TypeVar('T')


def foo(a: T) -> T:
    return a()

This template suites my question above, but actually, my need is a little bit different that I need to work more. Below I include my problem and solution:

Problem: I want to use the with keyword like this:

with open_page(PageX) as page:
    page.method_x() # method x is from PageX

Solution

from typing import TypeVar, Type, Generic

T = TypeVar('T')

def open_page(cls: Type[T]):
    class __F__(Generic[T]):

        def __init__(self, cls: Type[T]):
            self._cls = cls

        def __enter__(self) -> T:
            return self._cls()

        def __exit__(self, exc_type, exc_val, exc_tb):
            pass

    return __F__(cls)

So, when I use with PyCharm, it's able to suggest method_x when I pass PageX into with open_page(PageX) as page:

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

1 Comment

Fantastic solution, this worked perfectly for my use case

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.