How to deal with Generics in Python?

I have a question about generics in Python.
It’s about the return value of a method, and specifically I’m looking for a way to have a generic return type.

For example in C# I have something like this:

public async Task<R> PostAsync<T, R>(string url, T body) {
 return JsonConvert.DeserializeObject<R>(responseJson);

R is the response type, T the type of the body.
So the point is to return a type of R.
Can I implement something like this in Python at all?
Sorry if the question seems weird, I’m completely new to Python, originally coming from C# and currently working my way into Python a bit.

Thanks a lot for your help!

>Solution :

If your goal is to have proper type annotations for the sake of static type checkers, you can do something like this:

from typing import Type, TypeVar

R = TypeVar("R")

class BodyType:

class MyClass:
    async def post(self, url: str, body: BodyType, return_class: Type[R]) -> R:
        # Do the thing...
        return return_class()

Note that since Python is not statically typed, there is strictly speaking no real equivalent to generic methods/functions. There is no special syntax for indicating the type argument for a function. You can achieve a similar construct by simply passing the class as an argument to the method.

Generic types do exist though. You can create your own by inheriting from the typing.Generic base class. But again, they don’t really matter at runtime and exist mainly for the benefit of static type checkers.

As mentioned in the comments, have a look at the typing module and PEP 484 for more details about available tools for type hints.

Leave a Reply