jeudi 19 décembre 2019

Design style for using **kwargs in Python? [closed]

I have this current scenario:

  1. File A and B uses function from file C.
  2. File A sends many necessary arguments to file C by calling functions in C that uses **kwargs.
  3. However, file B does not require kwargs in file C, and so functions in file B using those in file C raises a KeyError since it doesn't feed in arguments from **kwargs.

What is the best design decision to deal with this? For example, I have thought of simply initializing the kwargs dict with some empty variable if the arguments are non available, which only occurs if file B calls the functions in C. However, is there a cleaner way to do this?

Example code:

class TestObject():
    """
    c and d are optional arguments. 
    Ideally, we want file B to use its default arg values when it doesn't give any kwargs input to fn_C.
    """
    def __init__(self, c=0.1, d=0.2):
        self.c = c
        self.d = d

# file C function
def fn_C(a, b, **kwargs):
    extra = TestObject(c=kwargs['c'], d=kwargs['d']) # raises key error when fn_B calls

    return a + b

# file A function
def fn_a(a1, a2):
    k = a1 + a2 + fn_c(1, 2, c=3, d=4)

    return k

# file B function
def fn_b(b1, b2):
    k = a1 + a2 + fn_c(1, 2)

    return k

Aucun commentaire:

Enregistrer un commentaire