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)
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.
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.
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.
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}.
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
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With