简体   繁体   中英

Is it acceptable to use a function return value as a keyword argument default value?

I have a function plot_variables(xy=var_combinations(), colors=set_colors()) where var_combinations() returns some default combinations of variables to be plotted and set_colors() returns a dict mapping colors to some herein irrelevant strings. xy and colors are later used as such:

def plot_variables(xy=var_combinations(), colors=set_colors()):
...stuff...   

    for i, (x, y) in enumerate(xy):
            axs1[i].scatter(data[x], data[y], c=data.irrelevant.map(colors))

...stuff...

This works as I want - xy and colors can either be left as default, or set manually by passing variables or a dict to plot_variables() , but is that the 'best' (or most pythonic) way to set the default values for those kwargs?

Thank you!

You can do this but realize that the function being called to create your default value is called exactly once when the primary function is defined. It's not called every time the primary function is invoked. This isn't the clearest way to express your intention.

> A = 1
> def foo():
>     print('foo')
>     return A

> def bar(arg=foo()):
>     print(arg)
foo

> bar()
1

> A = 2
> bar()
1

More readable, easier to reason, and (IMO) more pythonic would be something like this:

DEFAULT_XY = var_combinations()
DEFAULT_COLORS = set_colors()

def plot_variables(xy=None, colors=None):
    if xy is None:
        xy = DEFAULT_XY
    if colors is None:
        colors = DEFAULT_COLORS
    # ...

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