简体   繁体   中英

How to pass optional python arguments to sub-functions with optional arguments

Given a simple Python function with an optional argument, like:

def wait(seconds=3):
    time.sleep(seconds)

How do I create a function that calls this and passes on an optional argument? For example, this does NOT work:

def do_and_wait(message, seconds=None):
    print(message)
    wait(seconds)

Note : I want to be able to call wait from other functions with the optional seconds argument without having to know and copy the current default seconds value in the underlying wait function to every other function which calls it.

As above, if I call it with the optional argument, like do_and_wait(2) then it works, but trying to rely on wait 's default, eg calling it like do_and_wait() causes a TypeError because inside wait seconds == None.

Is there a simple and clean way to make this work? I know I can abuse kwargs like this:

def do_and_wait(message, **kwargs):
    print(message)
    wait(**kwargs)

But that seems unclear to the reader and user of this function since there is no useful name on the argument.

Note: This is a stupidly simplified example.

I don't think you've quite explained your problem completely because I don't expect an answer should be this simple, but I would just use the same default value (and data type) in do_and_wait() as wait() uses, like so:

def do_and_wait(message, seconds=3):
    print(message)
    wait(seconds)

I understand you've simplified your question, but I think you mean how one can call a function with optional arguments that could be None. Does the following work for you?

import time

def func1(mess, sec):
  if sec != None:
    time.sleep(sec)
  print(mess)


func1('success', sec=None)

After thinking a bit more, I came up with something like this; Han's answer suggested this and reminded me that I think PEP even suggests it somewhere. This especially avoids having to know and copy the default value into any function that calls wait and wants to support a variable value for seconds .

def wait(seconds=None):
    time.sleep(seconds if seconds is not None else 3)

def do_and_wait(message, seconds=None):
    print(message)
    wait(seconds)

def something_else(callable, seconds=None):
    callable()
    wait(seconds)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM