Sunday, March 19, 2017

Generic Decorator to Convert Empty Arguments to None

Generic Decorator to Convert Empty Arguments to None

In the following, a generic decorator is developed to convert all the empty arguments of any arbitrary function to None.

def EmptyToNone(func):
    def innerFunc(*args, **kwargs):
        args = (None if item == "" else item for item in args)
        kwargs = {k:(None if v == "" else v) for k, v in kwargs.items()}
        return func(*args, **kwargs)
    return innerFunc

@EmptyToNone
def testingFunc(a, b, c, *d, **e):
    print(a, b, c, d, e)

testingFunc("", 1, "", 2, "", k="aaa")

Result: 

None 1 None (2, None) {'k': 'aaa'}

 


Copyright ©2017, Software Developer, All rights reserved.
See Contents

No comments:

Post a Comment