Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function definition like range

Suppose I wanted to write a function similar to range

Recall that range has a one argument and 2/3 argument form:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object

If I wanted the method or function to have the same interface, is there a more elegant way than this:

def range_like(*args):
    start,stop,step=[None]*3
    if len(args)==1:
        stop=args[0]
    elif len(args)==2:
        start,stop=args
    elif len(args)==3:
        start,stop,step=args
    else:
        raise ValueError       
    print(start,stop,step)
like image 863
the wolf Avatar asked Jun 17 '13 19:06

the wolf


People also ask

What are the 4 types of functions?

The types of functions can be broadly classified into four types. Based on Element: One to one Function, many to one function, onto function, one to one and onto function, into function.

What is the difference between range and function?

The domain of a function is the set of values that we are allowed to plug into our function. This set is the x values in a function such as f(x). The range of a function is the set of values that the function assumes. This set is the values that the function shoots out after we plug an x value in.

IS range is a function?

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

What is range in function definition?

The range of a function is a set of all the images of elements in the domain. In this example, the range of the function is {2,3}.


2 Answers

Not much to suggest here, but one alternative could be using optional arguments and swapping the first two if only one were provided:

def range_like(start, stop=None, step=1):
    if stop is None:
        start, stop = 0, start
    ...
like image 188
mgibsonbr Avatar answered Sep 28 '22 23:09

mgibsonbr


i would write this as:

def range_like(start=None, stop=None, step=1):
    if stop is None:
        start, stop = stop, start
    ...

if that does what you want?

[update] you can also add:

    if stop is start is None:
        raise ValueError()

also, to use sentinel objects instead of None (this isn't normal in Python, but you see it sometimes):

NOTSET = object()
def range_like(start=NOTSET, stop=NOTSET, step=1):
    if stop is NOTSET:
        start, stop = stop, start

which allows None as an argument.

like image 22
andrew cooke Avatar answered Sep 28 '22 22:09

andrew cooke