Issue
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(5)))
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!!!
Solution
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
else:
start = a
stop = b
step = c
print(f"{start = }, {stop = }, {step = }")
foo(2)
foo(1,2)
foo(1,2,3)
Answered By – matszwecja
Answer Checked By – Robin (AngularFixing Admin)