Skip to content
Advertisement

Does python functools.singledispatch work with Generator type?

I extended the example at https://docs.python.org/3/library/functools.html#functools.singledispatch by adding a registration for generator type

JavaScript

while it works with list, it doesn’t seem to work with generator with error like

JavaScript

Is it expected that singledispatch does not work with generator?

Advertisement

Answer

typing.Generator is a type hint, not a type. You need types.GeneratorType.

JavaScript

Objects are not considered instances of type hints according to isinstance, which is what singledispatch uses to decide which function to use for a given argument. With this change, you’ll get the expected output

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement