Is there a way to use required arguments after default arguments? (Like the default python range())


I was programming a class trying to recreate the default python range-class but realised that the initialisation behaves kind of differently than usual.

Usually the required arguments of a function have to be infront of the default arguments f.e.:

def foo(a, b, c='bar'):
    return a, b, c

But in the case of range() you use it like this. range(start, stop, step). Where stop is the only required argument. So basically:

print(list(range(2, 6)))
print(list(range(0, 10, 2)))
>>[0, 1, 2, 3, 4]
>>[2, 3, 4, 5, 6]
>>[0, 2, 4, 6, 8]

Does this mean there is a way to write a function in a way that the required arguments don’t have to be the first ones? How excatlly does it work and how can I recreate it?

Thanks in advance!!!


Of course there is a way. If nothing else, you can do something like that:

def foo(a, b = None, c = None ):
    if not b and not c:
        start = 0
        stop = a
        step = 1
    elif not c:
        start = a
        stop = b
        step = 1
        start = a
        stop = b
        step = c
    print(f"{start = }, {stop = }, {step = }")


Answered By – matszwecja

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.