简体   繁体   中英

Passing method with args to another function with kwargs

I have two functions that differ by one argument that I would like to pass in accordingly based on a given case...

def func1(a, b, c):
    print a, b, c

def func2(a, b, c, d=False)
    print a, b, c, d

def run(func, **kwargs):
     if b is None:
         b = 999
     func(**kwargs)

run(func1, a=1, b=None, c=3)

I am unable to get this to work as it complains that b is being referenced before assignment.

def func1(a, b, c):
    print a, b, c

def func2(a, b, c, d=False):
    print a, b, c, d

def run(func, **kwargs):
    if 'b' in kwargs:
        if kwargs['b'] is None:
            kwargs['b'] = 999
    func(**kwargs)

run(func1, a=1, b=None, c=3)

Access b by:

if kwargs['b'] is None:

So, The run function would be:

def run(func, **kwargs):
     kwargs['b'] = kwargs.get('b', 999)
     func(**kwargs)

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