简体   繁体   中英

How to set all default parameter values to None at once

I have a method with n parameters. I want to set all the default parameter value to None , eg:

def x(a=None,b=None,c=None.......z=None): 

Is there any built in method to set all the parameter values to None at once if they are not set default to None while writing the method?

For a plain function, you can set __defaults__ :

def foo(a, b, c, d):
    print (a, b, c, d)

# foo.__code__.co_varnames is ('a', 'b', 'c', 'd')
foo.__defaults__ = tuple(None for name in foo.__code__.co_varnames)

foo(b=4, d=3)  # prints (None, 4, None, 3)

If you literally want to add None as default to every argument you need some sort of decorator approach. If it's only about Python 3 then inspect.signature can be used:

def function_arguments_default_to_None(func):
    # Get the current function signature
    sig = inspect.signature(func)
    # Create a list of the parameters with an default of None but otherwise
    # identical to the original parameters
    newparams = [param.replace(default=None) for param in sig.parameters.values()]
    # Create a new signature based on the parameters with "None" default.
    newsig = sig.replace(parameters=newparams)
    def inner(*args, **kwargs):
        # Bind the passed in arguments (positional and named) to the changed
        # signature and pass them into the function.
        arguments = newsig.bind(*args, **kwargs)
        arguments.apply_defaults()
        return func(**arguments.arguments)
    return inner


@function_arguments_default_to_None
def x(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z): 
    print(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z)

x()
# None None None None None None None None None None None None None None 
# None None None None None None None None None None None None

x(2)
# 2 None None None None None None None None None None None None None 
# None None None None None None None None None None None None

x(q=3)
# None None None None None None None None None None None None None None 
# None None 3 None None None None None None None None None

However that way you will loose introspection for the function because you manually altered the signature.

But I suspect that there are probably better way to solve the problem or avoiding the problem completely.

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