Can we type generic functions in the same way as other objects?

When creating an empty list i can pass the type even if the list is empty on initialization:

# all these are the same
my_list: list[int] = []
my_list: list[int] = list() 
my_list = list[int]() 

Typically i take the last one as it feels both more modern and concise.

My surprise is that this don’t apply to functions:

def dummy_container[T]() -> list[T]:
   return list()


my_list = dummy_container[int]()  # TypeError function / method is not subscriptable

# i expect that the list is created with type list[int]

I think it would be nice to allow this syntax to be a thing, I imagine that this may be already proposed but I could not find it.

It seems as the current behaviour is a TypeError, so probably this change would be mostly backwards compatible, except for the code that relies on catching the error of subscripting a function, which I see a bit wild.

Still I guess if this is ok for the classes and no big issues with backwards compatibility was found, probably will be also ok for functions and methods.

You can check out:

1 Like

fair enough thanks, good to see that people is working on it, I guess we can just delete my post, it is treated here: PEP 718: subscriptable functions