bjd2385 bjd2385 - 24 days ago 5
Python Question

Optional return type annotations?

I have a function that will either return a generator (

) or
, depending upon the value of an argument. For example:

def foo(switch: bool) -> list: # return type of list || types.GeneratorType
... # create some generator object named f1
if switch:
return list(f1)
return f1

How do I tell it that I can optionally return a list or another type? Or, for that matter, what about a bunch of different types?

I've looked over documentation on a module
but haven't as of yet found any methods there that allow for this. I haven't been able to find any examples by Googling either.


The two solutions that immediately spring to mind are:

  1. Make a Union type

    def foo(switch: bool) -> Union[list, GeneratorType]:

    which means "returns either list or generator" (you could also use Generator and List); or

  2. Type based on the behaviour you can expect from either return value, e.g. that they are Iterable:

    def foo(switch: bool) -> Iterable:  

In both cases you could also provide more detail: list or generator/iterable of what?

That said, something that returns either a list or a generator sounds like an odd interface, and it would be helpful to provide a bit more context around what consumers of your function should expect to do with whatever they receive. It may be that:

  • a single function with two different returns isn't the right interface design; or
  • rather than list you could use the more general Sequence, to permit e.g. tuples to be used instead.