Python3:定义自定义初始化错误的正确方法
Python3: Correct way to define custom init error
假设您有一个自定义 class,它有一些必需的参数(您不能为其提供默认值)并且您希望在未提供这些必需的参数时引发自定义错误。
执行此操作的正确 pythonic 方法是什么?
现在我有这样的东西:
class MyClassInitError(Exception):
def __init__(self, missing_kwargs):
self.message = "Some required key word arguments were not present {missing}".format(missing=missing_kwargs)
class MyClass():
# required arguments for this class that can not have pre-defined values
_required_kwargs = ["arg1", "arg2", "arg3",...]
# required arugments for this class that can have pre-defined values
_predef_kwargs = {"pre_arg1":1, "pre_arg2":2, ...}
def __init__(self, **kwargs):
try:
# leverage set class to get keys of required args not in the passed kwargs
missing_kwargs = list(set(self._required_kwargs)-set(kwargs.keys()))
if missing_kwargs:
raise MyClassInitError(missing_kwargs)
# set defaults for defaults not provided
for k, w in self._predef_kwargs.items():
if k not in kwargs.keys():
kwargs[k] = w
PEP 3102 引入了需要关键字参数的语法,因此无需编写自己的代码来进行验证:
def __init__(self, *, arg1, arg2, arg3, pre_arg1=1, pre_arg2=2):
pass # TODO: use the args, no need to check them
假设您有一个自定义 class,它有一些必需的参数(您不能为其提供默认值)并且您希望在未提供这些必需的参数时引发自定义错误。
执行此操作的正确 pythonic 方法是什么?
现在我有这样的东西:
class MyClassInitError(Exception):
def __init__(self, missing_kwargs):
self.message = "Some required key word arguments were not present {missing}".format(missing=missing_kwargs)
class MyClass():
# required arguments for this class that can not have pre-defined values
_required_kwargs = ["arg1", "arg2", "arg3",...]
# required arugments for this class that can have pre-defined values
_predef_kwargs = {"pre_arg1":1, "pre_arg2":2, ...}
def __init__(self, **kwargs):
try:
# leverage set class to get keys of required args not in the passed kwargs
missing_kwargs = list(set(self._required_kwargs)-set(kwargs.keys()))
if missing_kwargs:
raise MyClassInitError(missing_kwargs)
# set defaults for defaults not provided
for k, w in self._predef_kwargs.items():
if k not in kwargs.keys():
kwargs[k] = w
PEP 3102 引入了需要关键字参数的语法,因此无需编写自己的代码来进行验证:
def __init__(self, *, arg1, arg2, arg3, pre_arg1=1, pre_arg2=2):
pass # TODO: use the args, no need to check them