Tuan Chau
Tuan Chau

Reputation: 1333

Python return typing dynamically based on parameter

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?

Upvotes: 4

Views: 1724

Answers (1)

Tuan Chau
Tuan Chau

Reputation: 1333

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:

Upvotes: 2

Related Questions