python - Optional Parameters, certain combination of them required -


i have general question specific use case.

optional parameters easy enough: def func(a, b, c=none): ... , anywhere c might used in body write if c: first, or along lines. when combination of parameters required? general case consider arbitrary situation of exact parameters exist or not. function def func(a, b, c=none, d=none, e=none, f=none): ... include silly things like: provide c , d not e , f, or provide e only, or provide @ least 3 of c, d, e, , f. use case doesn't require such generality.

for def func(a, b, c=none, d=none): ..., want 1 of c , d provided.

solutions i've thought of include:
- in body, manually check how many of c , d not none, , if it's not 1, return error saying 1 needs specified
ex.

def func(a, b, c=none, d=none):     how_many_provided = len([arg arg in [c, d] if arg]) # count non-none optional args     if not how_many_provided == 1:         return "hey, provide 1 of 'c' , 'd'"     if c:         # stuff if c provided     elif d:         # stuff if d provided 

- change function def func(a, b, e, f): ... e represents either c or d , f indicates 1 of e represents.
ex.

def func(a, b, e, f):     if f == 'c':         # stuff if c provided, e c     if f == 'd':         # stuff if d provided, e d 

these work, standard/accepted/pythonic way of doing this?

you use keyword args dict:

def func(a, b, **kwargs):   valid_args = len(kwargs) == 1 , ('c' in kwargs or 'd' in kwargs)    if not valid_args:       return "hey, provide 1 of 'c' , 'd'"   if 'c' in kwargs:       # stuff if c provided   elif 'd' in kwargs:       # stuff if d provided 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -