Dynamic default arguments in python functions

前端 未结 4 732
误落风尘
误落风尘 2021-01-12 19:22

I have a need for functions with default arguments that have to be set at function runtime (such as empty lists, values derived from other arguments or data taken from the d

4条回答
  •  一向
    一向 (楼主)
    2021-01-12 20:20

    You could do something like this:

    def getArg():
      try:
          return arg
      except NameError:
          return 0
    
    def foo(x, y=getArg):
        y = y()
        print(y)
    
    foo(1) # Prints 0 (Default)
    
    arg = 7 # Set by argparse?
    
    foo(2)           # Prints 7 (Dynamic global)
    foo(3, lambda:9) # Prints 9 (Dynamic passed)
    

提交回复
热议问题