diff --git a/src/polyfills/stdlib/README.md b/src/polyfills/stdlib/README.md index 04d5b84..322ea38 100644 --- a/src/polyfills/stdlib/README.md +++ b/src/polyfills/stdlib/README.md @@ -5,6 +5,7 @@ Backporting of some of the features natively available in newer Python versions: - [**`bool`**](future_types/bool.py) class (as well as `True` and `False`) - [**`sorted()`**](functions.py) function (`Python 2.4`) - [**`sum()`**](functions.py) function (`Python 2.3`) +- [**`enumerate()`**](functions.py) function (`Python 2.3`) - [**`print()`**](print.py) function (keyword arguments such as `end` or `sep` were added in `Python 3.3`, see module docstring for more details) - [**`NotImplementedError`**](exceptions.py) exception (`Python 2.2`) - [`set()`](sets.py) class (`Python 2.4`) diff --git a/src/polyfills/stdlib/functions.py b/src/polyfills/stdlib/functions.py index c99c6e7..d3dec29 100644 --- a/src/polyfills/stdlib/functions.py +++ b/src/polyfills/stdlib/functions.py @@ -13,6 +13,42 @@ "sorted", ] +def enumerate(__iterable, start=0): + """ It generates a sequence of tuples containing a count + (from start which defaults to 0) and the values obtained from + iterating over iterable. + + This is a backport of the Python `enumerate` built-in function + (introduced in 2.3) that works down to Python 2.1 (tested). + + Args: + __iterable (Iterable): The iterable to enumerate. + start (int): The value to start from. + + Returns: + enumerate (zip): An enumerate object. + """ + try: + range_func = xrange # pyright: ignore[reportUndefinedVariable] + except NameError: + range_func = range + + return zip(range_func(start, start + len(__iterable)), __iterable) + +class EnumerateTestCase(_unittest.TestCase): + def test_enumerate(self): + """Test the `enumerate` function.""" + self.assertEqual( + list(enumerate(["a", "b", "c"])), + [(0, "a"), (1, "b"), (2, "c")], + "Enumerate should work" + ) + self.assertEqual( + list(enumerate(["a", "b", "c"], 10)), + [(10, "a"), (11, "b"), (12, "c")], + "Enumerate should work with a start value" + ) + def sum( __iterable, # type: list[int|float] start = 0 # type: int