In #Python do you use any conventions to keep track of which functions return generators and which ones return iterables? Do you name your functions or variables in a specific way?

I like generators for lazy execution, but I've been bitten by accidentally iterating over them more than once. It can be tricky to debug this kind of mistake.

I've considered designing all my functions in a module to return just generators or just iterables, but it feels overly restrictive.

Follow

@sourcenouveau Is this independent of using type hints? My functions returning containers usually return abstract protocol types, so f() -> Iterator[T] for generator type things and f() -> Iterable[T] for iterable type things (or Sequence or MutableSequence or whatever).

I don’t think a type checker is going to stop you from iterating over it twice, though, so I guess you still have to know the signature.

@pganssle Type hints would help in some cases, where the IDE can highlight misuses. I work in a code base where type hints are not used so sometimes I overlook them. Thanks!

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.