Home > Back-end >  How to avoid repeating the default argument value for a function called from another function?
How to avoid repeating the default argument value for a function called from another function?

Time:11-16

Consider some function that accepts a default value:

def print_number(number=42):
    print(number)

Now you might happen to want to use this from another function, but the argument is still provided by the user:

def print_number_twice(number=42):
    print_number(number)
    print_number(number)

And here you happen to repeat the default value, which can be annoying for refactoring later. Someone might change the default only in one place, reading to weird behavior.

I tried this:

def print_number_twice(number=None):

But in Python, None is still a valid argument, so it will print "None". Is there a convenient way to use the nested functions default argument without repeating it? I still want to allow caller of print_number_twice to omit the argument.

CodePudding user response:

You could check for None, like so:

def print_number_twice(number=None):
    if number is None:
        print_number()
        print_number()
    else:
        print_number(number)
        print_number(number)

However personally I think it would be better to just define the default arguments to both functions. If you're concerned about what happens if you change one default but forget to change the other, perhaps use a global constant, something like:

DEFAULT_NUM = 42

def print_number(number=DEFAULT_NUM):
    print(number)

def print_number_twice(number=DEFAULT_NUM):
    print_number(number)
    print_number(number)
  • Related