pythonargument-passing

Order of default and non-default arguments


In Python, I understand that default arguments come at the end and that non-default arguments cannot follow a default argument. That is fine. Like for example:

>>> def foo(x=0, y):
        return x, y
SyntaxError: non-default argument follows default argument

That is OK as expected.

However, what about the case when I want that the first argument should be a default one? Like for example, as is apparent from the above code, x has to be the first argument and it should have a default value of 0.

Is it possible to do this? I am asking because even in the range function, I am guessing it is something like this:

def range(start=0, end):
    pass

So how is this done and if it is not possible, how is this implemented by range? Note that I am insisting on the first argument to be default, that is the entire point. I am using range as an example because it fits my problem perfectly. Of course one could implement range as def range(end, start=0), but that is not the point.


Solution

  • Well, range is C code which can do this slightly better. Anyways, you can do this:

    def range(start, stop=None):
        if stop is None: # only one arg, treat stop as start ...
            stop = start
            start = 0
        ...
    

    and document the function accordingly.