Return type of function returning a class


I have a function that returns a class created within the function, so something like this:

def foo(a, b):
    class Bar:
        def __init__(self, func):

    return Bar

I am not sure exactly how this should be typed. I’m currently trying with

from typing import Callable
def foo(a: int, b: str) -> Type["Bar"]:
    class Bar:
        def __init__(self, func: Callable):

    return Bar

but both mypy and Pycharm complain that Bar is not defined. I’ve tried both with and without from __future__ import annotations.

Is there a way to solve this?

I don’t know much about typing, but the type of a class is type, so shouldn’t you use -> type:?

1 Like

Thank you for your suggestion, but it won’t work for my use case

I just realized I didn’t have from __future__ import annotations in the module in question, only in the __main__ file. Adding the future import makes mypy happy.

However, if I use foo as a decorator within a class definition, like this

class Baz:
    @foo(1, 'a')
    def abc(self):

mypy will not find errors in the signature of abc (if the signature of Bar.__init__ is something like Bar.__init__(self, func: Callable[[int, int], str])).
I resolved this by adding a dummy base class for Bar

class BarBase:
   def __init__(self, func: Callable[[int, int], str]): ...

and change Bar to inherit from BarBase.