Skip to content

Commit

Permalink
feat(stdlib): Add enumerate function
Browse files Browse the repository at this point in the history
Fix #10, improve #14
  • Loading branch information
LukeSavefrogs committed Jan 30, 2024
1 parent eea4cb4 commit 8141af8
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/polyfills/stdlib/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
Expand Down
36 changes: 36 additions & 0 deletions src/polyfills/stdlib/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 8141af8

Please sign in to comment.