简体   繁体   中英

Python set parameter value for subsequent function calls

Is there an option in Python to define a parameter values for some functions so that those values are used when the mentioned functions are called?

Something like this in TF Slim: https://www.tensorflow.org/api_docs/python/tf/contrib/framework/arg_scope

Example:

set_default_params(functions=[func_1, func_2], params=[param_1=value_1, param_2=value_2, param_3=value_3])

After this, when I call func_1() which has default params param_1=0 and param_2=None , it would actually get param_1=value_1 and param_2=value_2 without the need to set it manually when calling func_1() .

You can use functools.partial to set default parameters. This partially applies parameters to a given function.

import functools

def func(param, *args, **kwargs):
    print('param:', param)
    print('args:', *args)
    print('kwargs:', kwargs)

g = functools.partial(func, 21)      # sets default value for param to 21
g('arg1', 'arg2', 'arg3', kw='kwarg1')

Output:

param: 21
args: arg1 arg2 arg3
kwargs: {'kw': 'kwarg1'}

Note that a new function is returned from functools.partial and the default parameters aren't set in-place as your set_default_params call implies.

If you want to be able to set params in the future, you can use some kind of decorators to do it.

def kind_of_decorator(func, params):
    def wrapper(*args, **kwargs):
        return func(*args, **dict(kwargs, **params))
    return wrapper

def foo(x, y=2):
    return x + y

print(foo(1, 5)) # prints 6
print(foo(3))    # prints 5

new_foo = kind_of_decorator(foo, {'y': 0})

print(new_foo(1, y=5))  # prints 6
print(new_foo(3))       # prints 3
#print(new_foo(1, 5))   # an error "TypeError: bar() got multiple values for argument 'y'" be careful there. Now only kwargs are allowed for `y`

Maybe not quite in that form, but if you define a function with def function(arg={}) , then the arg argument's default value will persist between calls rather than being set to a new object. That means you could use:

def function1(arg1, arg2=None, arg3=None, args={"arg2": 42, "arg3": 43}):
    if arg2 is not None:
        args["arg2"] = arg2
    if arg3 is not None:
        args["arg3"] = arg3
    arg2, arg3 = args["arg2"], args["arg3"]
    print(arg1, arg2, arg3)

function1(1)  # prints 1 42 43; using default values for arg2 and arg3
function1(1, 2) # prints 1 2 43; replace arg2 but keep arg3
function1(1, arg3=3) # prints 1 2 3; replace arg3 but keep arg2 from previous call
function1(0)  # prints 0 2 3; both arg2 and arg3 persist from previous calls.

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