0

I'm trying to write a program which finds primes in a certain range. One of the things which I'm trying to do is allow the function to be called without all its arguments.

What I want to do is something like this:

def find_primes(start=1, stop, primes=None):

The primes variable will then be initialised to a blank list (I'm trying to make the program recursive).

However, this will cause an error because I cannot use a default value for an argument before all the required values.

One way I thought of doing this was:

def find_primes(start, stop=-1, primes=None):
    if primes is None:
        primes = []
    if stop = -1:
        stop = start
        start = 1

Basically, I can flip the variables if stop remained at its default, out-of-range value. However this seems quite hacky and I am hoping there is a better way of doing this.

An example of somewhere I know this is implemented is the range function, because I can call it as

range(stop)

or

range(start, stop[, step])

Is this possible to implement? Thanks in advance.

EDIT: In other languages, I could use function overloading:

def find_primes(stop):
    return find_primes(1, stop)
def find_primes(start, stop, primes=None)
    #Code

Does this exist in Python?

ratorx
  • 257
  • 1
  • 8
  • Possible duplicate of http://stackoverflow.com/questions/13366293/how-can-the-built-in-range-function-take-a-single-argument-or-three – jonrsharpe May 14 '16 at 15:44
  • Oh yeah. Thanks. I should have been more general when searching for the solution before posting. The *args method would definitely work. – ratorx May 14 '16 at 15:52

1 Answers1

0

Range is a built-in function, but if it was implemented in Python, it'd probably use the same "Hack" as you suggest. As Python doesn't have C-/Java-style function overloading, that "Hack" really is the only way to achieve this in Python without *args, and when you use None as default value (rather than the arbitrary -1) it could even be considered idiomatic:

def find_primes(start_or_stop, stop_or_none=None, primes=None):
    """
    find_primes([start], stop, [primes])
    """
    # ^ Communicate the semantics of the signature by the docstring,
    # like `range` does.   
    if primes is None:
        primes = []
    if stop_or_none is None:
        start, stop = 1, start_or_stop
    else:
        start, stop = start_or_stop, stop_or_none
das-g
  • 9,718
  • 4
  • 38
  • 80