-1

a few days ago I started working in my friend's startup as junior Python developer, we are the only employees.

I have noticed he sometimes writes strange code. For example this:

@pytest.fixture
def create_user_model_test_data():
    positive_numbers_iterator = (
        lambda n: type("DeclarativeParametrizedNumbersInfiniteIterator", (), {
            "__iter__": lambda self: self,
            "__next__": staticmethod(
                (
                    lambda n:
                    (
                        lambda arg_dict:
                        lambda: (
                            arg_dict.update({"n": arg_dict["n"] + 1}) or arg_dict["n"] - 1,
                        )
                    )
                    ({"n": n})
                )
                (n)
            )
        })
        ()
    )
    positive_numbers_starting_from_zero_iterator = positive_numbers_iterator(0)
    # FIXME: dont know why python needs a while to iterate a sequence but anyways
    while "1":
        for n in next(map(next, [positive_numbers_starting_from_zero_iterator])):
            if n == 20: return
            create_user(name=f"user-{n}", role=["admin", "user"][n % 2])

I recommended changing it by this:

N = -1
def iterate_numbers():
    N += 1
    return N

However, he said it is impure, not declarative and can't be parametrized. I said it's not a problem and that the declarative ways is ugly, but he replied that Python is ugly, you can write a simple declarative infinite iterator in Haskell, and now is considering rewriting the entire project in Haskell. I love Python and want to learn it, I don't know Haskell nor want to learn.

Please, tell me how to write a simple declarative parametrized pure infinite numbers sequence in Python without mutating global variables, I don't want to learn Haskell, I need to convince him to stick with Python.

EDIT: Note that the iterator can be written in only 1 line of code, which is nice, but I have formated it so you can easily understand it

Pablo
  • 37
  • 5

1 Answers1

3

This is a function which will return an infinite number generator. You can define the start as well.

def iterate_numbers(start=0):
    while True:
        yield start
        start += 1
Szabolcs
  • 3,990
  • 18
  • 38