Skip to content

Harden your code and your type hints with RepeatableIterable

License

LGPL-3.0, GPL-3.0 licenses found

Licenses found

LGPL-3.0
COPYING.LESSER
GPL-3.0
COPYING
Notifications You must be signed in to change notification settings

LLyaudet/python-repeatable-iterable

Repository files navigation

python-repeatable-iterable

PyPI-version-badge Downloads-badge Code-style:black:badge Imports:isort:badge Typecheck:mypy:badge Linting:pylint:badge CodeFactor-badge CodeClimateMaintainability-badge Codacy-badge GitHub-top-language-badge GitHub-license-badge PyPI-python-version-badge GitHub-code-size-in-bytes-badge

A new type RepeatableIterable for Python
and a way to obtain one instance

Since in Python an Iterator is an Iterable and that you cannot iterate multiple times on an iterator, you may encounter WTF bugs, even with type checking. This package provides possible solutions to this problem. See here for a discussion on this problem: https://stackoverflow.com/questions/63104689 (/what-is-the-pythonic-way-to-represent-an-iterable -that-can-be-iterated-over-mult).

Before:

def foo(iterable: Iterable):
    for that in iterable:
        bar(that)
    for that in iterable:
        # possible bug
        baz(that)

foo(something)

After solution 1:

from python_repeatable_iterable import RepeatableIterable

def foo(iterable: RepeatableIterable[object]):
    for that in iterable:
        bar(that)
    for that in iterable:
        baz(that)

something_else = RepeatableIterable(something)
foo(something_else)

After solution 2:

from python_repeatable_iterable import RepeatableIterable

def foo(iterable: Iterable):
    iterable = RepeatableIterable(iterable)
    for that in iterable:
        bar(that)
    for that in iterable:
        baz(that)

foo(something)

If you develop something where you have no control on what another dev might give you as input, you have 2 possibilities:

  • hope for the best ;),
  • or harden your code to have less support work to do :).

This applies if you dev something that is:

  • closed source or open source,
  • available to everyone on the Internet, available only to customers or colleagues that you may personally know or not.

Solution 2 above is a nice solution with a reasonable performance cost :).

About

Harden your code and your type hints with RepeatableIterable

Resources

License

LGPL-3.0, GPL-3.0 licenses found

Licenses found

LGPL-3.0
COPYING.LESSER
GPL-3.0
COPYING

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published