I need to make sure all the named parameters were passed to a method (I don't want any defaults). Is the following the best way to enforce it?
class X:
def func(self, **kwargs):
if set(kwargs.keys() != ('arg1', 'arg2', 'arg3'):
raise ArgException(kwargs)
asked Feb 2, 2011 at 3:34
max
52.8k60 gold badges224 silver badges380 bronze badges
3 Answers 3
For Python 2.x, Hugh's answer (i.e. just use named positional arguments) is your best bet.
For Python 3.x, you also have the option of requiring the use of keyword arguments (rather than merely allowing it) as follows:
class X(object):
def func(self, *, arg1, arg2, arg3):
pass
answered Feb 2, 2011 at 4:00
ncoghlan
41.9k11 gold badges77 silver badges83 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
class X(object):
def func(self, **kwargs):
required = set(['arg1','arg2','arg3'])
if not set(kwargs.keys()).issuperset(required):
raise ArgException(kwargs)
although you could just let the interpreter take care of it:
class X(object):
def func(self, arg1, arg2, arg3):
pass
answered Feb 2, 2011 at 3:42
Hugh Bothwell
57k9 gold badges91 silver badges103 bronze badges
1 Comment
max
+1 .. yes, see my comment to the question. I have no idea how I didn't know that..
Do you want to allow other arguments? If not:
class X(object):
def func(self, arg1, arg2, arg3):
pass
If yes:
class X(object):
def func(self, arg1, arg2, arg3, **kwargs):
pass
That's for all versions of Python.
answered Feb 2, 2011 at 9:27
Lennart Regebro
173k45 gold badges230 silver badges254 bronze badges
Comments
lang-py
def func( self, arg1, arg2, arg3 ).def func(self, a, b, c)... :)