适用于Python中自定义错误处理程序的命名范围

时间:2012-08-28 18:51:53

标签: python error-handling

我正在尝试为我的应用程序编写错误处理类。是否有必要每次都包含错误处理程序的完整路径?以下是我的代码。

应用程序名称/应用程序的名字/模型/ error.py

class UserError(Exception):
  """ User errors
  """

  def __init__(self, value):
    self.value = value

  def __str__(self):
    return repr(self.value)

我的班级功能:

from error import UserError

def doSomething(
  """ Some function
  """
  if (value == 2):
    pass
  else:
    raise UserError('Value is not 2')

从我的申请中调用如下: 来自错误导入UserError

try:
  print names['first']
except appname.model.error.UserError as e:
  print e

成长时:

>> appname.model.error.UserError: 'No file specified'

我是否必须始终将其称为“appname.model.error.UserError”?或者有没有办法将此错误称为UserError甚至error.UserError?我在哪里调整这个范围?在我更改应用程序的目录结构(甚至名称)时,似乎不是一个好主意,不是吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

from appname.model.error import UserError