I need to make sure all the named parameters were pa开发者_JAVA百科ssed 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)
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
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
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.
精彩评论