Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert that zero or only one of N given arguments is passed

Tags:

python

I have a definition like this

def bar(self, foo=None, bar=None, baz=None):
    pass

I want to make sure a maximum of one of foo, bar, baz is passed. I can do

if foo and bar:
    raise Ex()

if foo and baz:
    raise Ex()
....

But there got be something simpler.

like image 254
agiliq Avatar asked Nov 30 '22 19:11

agiliq


1 Answers

How about:

 initialisers = [foo, bar, baz]
 if initialisers.count(None) < len(initialisers) - 1:
     raise Ex()

It simply counts how many None are present. If they're all None or only one isn't then fine, otherwise it raises the exception.

like image 132
Scott Griffiths Avatar answered Dec 06 '22 10:12

Scott Griffiths