Home > Software design >  Sets the default value of a parameter based on the value of another parameter
Sets the default value of a parameter based on the value of another parameter

Time:09-17

So I want to create a function that generates consecutive numbers from 'start' to 'end' as many as 'size'. For the iteration, it will be calculated inside the function. But I have problem to set default value of parameter 'end'. Before I explain further, here's the code:

# Look at this -------------------------------
#                                           ||
#                                           \/
def consecutive_generator(size=20, start=0, end=(size start)):
    i = start
    iteration = (end-start)/size

    arr = []
    temp_size = 0

    while temp_size < size:
        arr.append(i)

        i  = iteration
        temp_size  = 1

    return arr

# with default end, so the 'end' parameter will be 11
c1= consecutive_generator(10, start=1)
print(c1)

# with end set
c2= consecutive_generator(10, end=20)
print(c2)


As can be seen above (on the default value of the 'end' parameter), what I want to achieve is the 'end' parameter whose default value is 'start' 'size' parameters (then the iteration will be 1)

The output will definitely be an error. So how can i do this? (this is my first time asking on stackoverflow sorry if i made a mistake)

CodePudding user response:

This is a pretty standard pattern:

def consecutive_generator(size=20, start=0, end=None):
   if end is None:
       end = size   start

CodePudding user response:

According to Python's document,

Default parameter values are evaluated from left to right when the function definition is executed.

So default values of parameters are can't evaluated from other dynamic values which are passed when the function called.

You should use the distinguishable value like None for the default value. Then you can check it and evaluate proper default value dynamically. For example,

def consecutive_generator(size=20, start=0, end=None):
    if end is None:
        end = size   start
    ...

If you need None as a valid value passed from caller, you can use other object or something to distinguish from valid value.

default_end = object()
def consecutive_generator(size=20, start=0, end=default_end):
    if end is default_end:
        end = size   start
    ...

CodePudding user response:

The default way is as Samwise said but there is an alternative solution that might work just as well.

def consecutive_generator(size=20, start=0, **kwargs):
   end = kwargs.get('end', size start)

This method allows you to get end if it exists or simply set the value of end if it doesn't.

To call it, this method does require that the function call have the parameter end specified if you want to set it to something other than the default.

consecutive_generator(20, 0, end=50)

dict.get

And perhaps consider checking out the documentation for range and numpy.linspace

  • Related