Python3:定义自定义初始化错误的正确方法

时间:2017-09-19 10:07:01

标签: python-3.x exception-handling

假设您有一个具有一些必需参数的自定义类(您无法为其提供默认值),并且您希望在未提供这些必需参数时引发自定义错误。

这样做的正确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

1 个答案:

答案 0 :(得分:3)

PEP 3102引入了要求关键字参数的语法,因此无需编写自己的代码来进行验证:

 def __init__(self, *, arg1, arg2, arg3, pre_arg1=1, pre_arg2=2):
     pass # TODO: use the args, no need to check them