[ACCEPTED]-Order of default and non-default arguments-argument-passing

Accepted answer
Score: 11

Well, range is C code which can do this slightly 2 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 1 the function accordingly.

Score: 3

There are a couple approaches. The first 13 would be to switch the arguments in the 12 function, if some of the arguments are "None". That 11 would work like this.

def range1(value, end=None):
    if end == None:
        end = value
        value = 0
    return _generate_range_values(value, end)

The other primary method 10 would be to have your function get a list 9 of all arguments it receives. Then it can 8 decide what to do, based on the number of 7 arguments.

def range2(*args):
    if len(args) == 1:
        start = 0
        end = int(args[0])
    elif len(args) == 2:
        start = int(args[0])
        end = int(args[1])
    return _generate_range_values(start, end)

The third would be to encourage 6 users to pass named arguments to your function, which 5 makes the order less important.

def range3(end, start=0):
    return _generate_range_values(start, end)

Then users 4 would call it with the named start argument 3 when they wanted something besides 0. (Although 2 the named argument would not be required, it 1 keeps the code clear.

for i in range3(55, start=12)
Score: 2

It is not implemented by range. You can use *args or 2 **args and treat the tuple or the dict as you 1 want. For example:

def f(*args):
  if len(args) == 1:
     print "assuming the first is default"
  elif len(args) == 2:
     print "two arguments were passed"
     print "Complaining"
Score: 1

You can handle the Exceptions yourself if 1 you really want that

def Range(start=0, end=None):
    if end is None:
        raise AttributeError("end value not specified")
Score: 1

I don't have the code for range, but I'm 2 certain it performs this kind of trick:

def range(start, stop=None, step=1):
    if stop is None:
        start, stop = 0, start

edit: Code 1 corrected per martineau's comment.

Score: 0

For a function with the first default value 1 parameter to be followed by other parameters:

def fn(first=value, *rest):
    # code


def fn(first=1, *rest):

fn(11, 2, 3)

More Related questions