PageRenderTime 56ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/exceptions/interp_exceptions.py

https://bitbucket.org/dac_io/pypy
Python | 762 lines | 736 code | 7 blank | 19 comment | 14 complexity | 0cd9e21711597170ef25fcd2cdc54096 MD5 | raw file
  1. """Python's standard exception class hierarchy.
  2. Before Python 1.5, the standard exceptions were all simple string objects.
  3. In Python 1.5, the standard exceptions were converted to classes organized
  4. into a relatively flat hierarchy. String-based standard exceptions were
  5. optional, or used as a fallback if some problem occurred while importing
  6. the exception module. With Python 1.6, optional string-based standard
  7. exceptions were removed (along with the -X command line flag).
  8. The class exceptions were implemented in such a way as to be almost
  9. completely backward compatible. Some tricky uses of IOError could
  10. potentially have broken, but by Python 1.6, all of these should have
  11. been fixed. As of Python 1.6, the class-based standard exceptions are
  12. now implemented in C, and are guaranteed to exist in the Python
  13. interpreter.
  14. Here is a rundown of the class hierarchy. The classes found here are
  15. inserted into both the exceptions module and the `built-in' module. It is
  16. recommended that user defined class based exceptions be derived from the
  17. `Exception' class, although this is currently not enforced.
  18. BaseException
  19. +-- SystemExit
  20. +-- KeyboardInterrupt
  21. +-- GeneratorExit
  22. +-- Exception
  23. +-- StopIteration
  24. +-- StandardError
  25. | +-- BufferError
  26. | +-- ArithmeticError
  27. | | +-- FloatingPointError
  28. | | +-- OverflowError
  29. | | +-- ZeroDivisionError
  30. | +-- AssertionError
  31. | +-- AttributeError
  32. | +-- EnvironmentError
  33. | | +-- IOError
  34. | | +-- OSError
  35. | | +-- WindowsError (Windows)
  36. | | +-- VMSError (VMS)
  37. | +-- EOFError
  38. | +-- ImportError
  39. | +-- LookupError
  40. | | +-- IndexError
  41. | | +-- KeyError
  42. | +-- MemoryError
  43. | +-- NameError
  44. | | +-- UnboundLocalError
  45. | +-- ReferenceError
  46. | +-- RuntimeError
  47. | | +-- NotImplementedError
  48. | +-- SyntaxError
  49. | | +-- IndentationError
  50. | | +-- TabError
  51. | +-- SystemError
  52. | +-- TypeError
  53. | +-- ValueError
  54. | +-- UnicodeError
  55. | +-- UnicodeDecodeError
  56. | +-- UnicodeEncodeError
  57. | +-- UnicodeTranslateError
  58. +-- Warning
  59. +-- DeprecationWarning
  60. +-- PendingDeprecationWarning
  61. +-- RuntimeWarning
  62. +-- SyntaxWarning
  63. +-- UserWarning
  64. +-- FutureWarning
  65. +-- ImportWarning
  66. +-- UnicodeWarning
  67. +-- BytesWarning
  68. """
  69. from pypy.interpreter.baseobjspace import Wrappable
  70. from pypy.interpreter.typedef import (TypeDef, GetSetProperty, descr_get_dict,
  71. descr_set_dict, descr_del_dict)
  72. from pypy.interpreter.gateway import interp2app
  73. from pypy.interpreter.error import OperationError
  74. from pypy.rlib import rwin32
  75. def readwrite_attrproperty_w(name, cls):
  76. def fget(space, obj):
  77. return getattr(obj, name)
  78. def fset(space, obj, w_val):
  79. setattr(obj, name, w_val)
  80. return GetSetProperty(fget, fset, cls=cls)
  81. class W_BaseException(Wrappable):
  82. """Superclass representing the base of the exception hierarchy.
  83. The __getitem__ method is provided for backwards-compatibility
  84. and will be deprecated at some point.
  85. """
  86. w_dict = None
  87. args_w = []
  88. def __init__(self, space):
  89. self.w_message = space.w_None
  90. def descr_init(self, space, args_w):
  91. self.args_w = args_w
  92. if len(args_w) == 1:
  93. self.w_message = args_w[0]
  94. else:
  95. self.w_message = space.wrap("")
  96. def descr_str(self, space):
  97. lgt = len(self.args_w)
  98. if lgt == 0:
  99. return space.wrap('')
  100. elif lgt == 1:
  101. return space.str(self.args_w[0])
  102. else:
  103. return space.str(space.newtuple(self.args_w))
  104. def descr_unicode(self, space):
  105. w_str = space.lookup(self, "__str__")
  106. w_base_type = space.gettypeobject(W_BaseException.typedef)
  107. w_base_str = w_base_type.dict_w["__str__"]
  108. if not space.is_w(w_str, w_base_str):
  109. w_as_str = space.get_and_call_function(w_str, space.wrap(self))
  110. return space.call_function(space.w_unicode, w_as_str)
  111. lgt = len(self.args_w)
  112. if lgt == 0:
  113. return space.wrap(u"")
  114. if lgt == 1:
  115. return space.call_function(space.w_unicode, self.args_w[0])
  116. else:
  117. w_tup = space.newtuple(self.args_w)
  118. return space.call_function(space.w_unicode, w_tup)
  119. def descr_repr(self, space):
  120. if self.args_w:
  121. args_repr = space.str_w(space.repr(space.newtuple(self.args_w)))
  122. else:
  123. args_repr = "()"
  124. clsname = self.getclass(space).getname(space)
  125. return space.wrap(clsname + args_repr)
  126. def descr_getargs(self, space):
  127. return space.newtuple(self.args_w)
  128. def descr_setargs(self, space, w_newargs):
  129. self.args_w = space.fixedview(w_newargs)
  130. def descr_getitem(self, space, w_index):
  131. return space.getitem(space.newtuple(self.args_w), w_index)
  132. def getdict(self, space):
  133. if self.w_dict is None:
  134. self.w_dict = space.newdict(instance=True)
  135. return self.w_dict
  136. def setdict(self, space, w_dict):
  137. if not space.is_true(space.isinstance( w_dict, space.w_dict )):
  138. raise OperationError( space.w_TypeError, space.wrap("setting exceptions's dictionary to a non-dict") )
  139. self.w_dict = w_dict
  140. def descr_reduce(self, space):
  141. lst = [self.getclass(space), space.newtuple(self.args_w)]
  142. if self.w_dict is not None and space.is_true(self.w_dict):
  143. lst = lst + [self.w_dict]
  144. return space.newtuple(lst)
  145. def descr_setstate(self, space, w_dict):
  146. w_olddict = self.getdict(space)
  147. space.call_method(w_olddict, 'update', w_dict)
  148. def descr_message_get(self, space):
  149. w_dict = self.w_dict
  150. if w_dict is not None:
  151. w_msg = space.finditem(w_dict, space.wrap("message"))
  152. if w_msg is not None:
  153. return w_msg
  154. if self.w_message is None:
  155. raise OperationError(space.w_AttributeError,
  156. space.wrap("message was deleted"))
  157. space.warn("BaseException.message has been deprecated as of Python 2.6",
  158. space.w_DeprecationWarning)
  159. return self.w_message
  160. def descr_message_set(self, space, w_new):
  161. space.setitem(self.getdict(space), space.wrap("message"), w_new)
  162. def descr_message_del(self, space):
  163. w_dict = self.w_dict
  164. if w_dict is not None:
  165. try:
  166. space.delitem(w_dict, space.wrap("message"))
  167. except OperationError, e:
  168. if not e.match(space, space.w_KeyError):
  169. raise
  170. self.w_message = None
  171. def _new(cls, basecls=None):
  172. if basecls is None:
  173. basecls = cls
  174. def descr_new_base_exception(space, w_subtype, __args__):
  175. exc = space.allocate_instance(cls, w_subtype)
  176. basecls.__init__(exc, space)
  177. return space.wrap(exc)
  178. descr_new_base_exception.func_name = 'descr_new_' + cls.__name__
  179. return interp2app(descr_new_base_exception)
  180. W_BaseException.typedef = TypeDef(
  181. 'BaseException',
  182. __doc__ = W_BaseException.__doc__,
  183. __module__ = 'exceptions',
  184. __new__ = _new(W_BaseException),
  185. __init__ = interp2app(W_BaseException.descr_init),
  186. __str__ = interp2app(W_BaseException.descr_str),
  187. __unicode__ = interp2app(W_BaseException.descr_unicode),
  188. __repr__ = interp2app(W_BaseException.descr_repr),
  189. __dict__ = GetSetProperty(descr_get_dict, descr_set_dict, descr_del_dict,
  190. cls=W_BaseException),
  191. __getitem__ = interp2app(W_BaseException.descr_getitem),
  192. __reduce__ = interp2app(W_BaseException.descr_reduce),
  193. __setstate__ = interp2app(W_BaseException.descr_setstate),
  194. message = GetSetProperty(W_BaseException.descr_message_get,
  195. W_BaseException.descr_message_set,
  196. W_BaseException.descr_message_del),
  197. args = GetSetProperty(W_BaseException.descr_getargs,
  198. W_BaseException.descr_setargs),
  199. )
  200. def _new_exception(name, base, docstring, **kwargs):
  201. # Create a subclass W_Exc of the class 'base'. Note that there is
  202. # hackery going on on the typedef of W_Exc: when we make further
  203. # app-level subclasses, they inherit at interp-level from 'realbase'
  204. # instead of W_Exc. This allows multiple inheritance to work (see
  205. # test_multiple_inheritance in test_exc.py).
  206. class W_Exc(base):
  207. __doc__ = docstring
  208. W_Exc.__name__ = 'W_' + name
  209. realbase = base.typedef.applevel_subclasses_base or base
  210. for k, v in kwargs.items():
  211. kwargs[k] = interp2app(v.__get__(None, realbase))
  212. W_Exc.typedef = TypeDef(
  213. name,
  214. base.typedef,
  215. __doc__ = W_Exc.__doc__,
  216. __module__ = 'exceptions',
  217. **kwargs
  218. )
  219. W_Exc.typedef.applevel_subclasses_base = realbase
  220. return W_Exc
  221. W_Exception = _new_exception('Exception', W_BaseException,
  222. """Common base class for all non-exit exceptions.""")
  223. W_GeneratorExit = _new_exception('GeneratorExit', W_BaseException,
  224. """Request that a generator exit.""")
  225. W_StandardError = _new_exception('StandardError', W_Exception,
  226. """Base class for all standard Python exceptions.""")
  227. W_BufferError = _new_exception('BufferError', W_StandardError,
  228. """Buffer error.""")
  229. W_ValueError = _new_exception('ValueError', W_StandardError,
  230. """Inappropriate argument value (of correct type).""")
  231. W_ImportError = _new_exception('ImportError', W_StandardError,
  232. """Import can't find module, or can't find name in module.""")
  233. W_RuntimeError = _new_exception('RuntimeError', W_StandardError,
  234. """Unspecified run-time error.""")
  235. W_UnicodeError = _new_exception('UnicodeError', W_ValueError,
  236. """Unicode related error.""")
  237. class W_UnicodeTranslateError(W_UnicodeError):
  238. """Unicode translation error."""
  239. object = None
  240. start = None
  241. end = None
  242. reason = None
  243. def descr_init(self, space, w_object, w_start, w_end, w_reason):
  244. # typechecking
  245. space.realunicode_w(w_object)
  246. space.int_w(w_start)
  247. space.int_w(w_end)
  248. space.realstr_w(w_reason)
  249. # assign attributes
  250. self.w_object = w_object
  251. self.w_start = w_start
  252. self.w_end = w_end
  253. self.w_reason = w_reason
  254. W_BaseException.descr_init(self, space, [w_object, w_start,
  255. w_end, w_reason])
  256. def descr_str(self, space):
  257. return space.appexec([space.wrap(self)], r"""(self):
  258. if self.end == self.start + 1:
  259. badchar = ord(self.object[self.start])
  260. if badchar <= 0xff:
  261. return "can't translate character u'\\x%02x' in position %d: %s" % (badchar, self.start, self.reason)
  262. if badchar <= 0xffff:
  263. return "can't translate character u'\\u%04x' in position %d: %s"%(badchar, self.start, self.reason)
  264. return "can't translate character u'\\U%08x' in position %d: %s"%(badchar, self.start, self.reason)
  265. return "can't translate characters in position %d-%d: %s" % (self.start, self.end - 1, self.reason)
  266. """)
  267. W_UnicodeTranslateError.typedef = TypeDef(
  268. 'UnicodeTranslateError',
  269. W_UnicodeError.typedef,
  270. __doc__ = W_UnicodeTranslateError.__doc__,
  271. __module__ = 'exceptions',
  272. __new__ = _new(W_UnicodeTranslateError),
  273. __init__ = interp2app(W_UnicodeTranslateError.descr_init),
  274. __str__ = interp2app(W_UnicodeTranslateError.descr_str),
  275. object = readwrite_attrproperty_w('w_object', W_UnicodeTranslateError),
  276. start = readwrite_attrproperty_w('w_start', W_UnicodeTranslateError),
  277. end = readwrite_attrproperty_w('w_end', W_UnicodeTranslateError),
  278. reason = readwrite_attrproperty_w('w_reason', W_UnicodeTranslateError),
  279. )
  280. W_LookupError = _new_exception('LookupError', W_StandardError,
  281. """Base class for lookup errors.""")
  282. def key_error_str(self, space):
  283. if len(self.args_w) == 0:
  284. return space.wrap('')
  285. elif len(self.args_w) == 1:
  286. return space.repr(self.args_w[0])
  287. else:
  288. return space.str(space.newtuple(self.args_w))
  289. W_KeyError = _new_exception('KeyError', W_LookupError,
  290. """Mapping key not found.""",
  291. __str__ = key_error_str)
  292. W_StopIteration = _new_exception('StopIteration', W_Exception,
  293. """Signal the end from iterator.next().""")
  294. W_Warning = _new_exception('Warning', W_Exception,
  295. """Base class for warning categories.""")
  296. W_PendingDeprecationWarning = _new_exception('PendingDeprecationWarning',
  297. W_Warning,
  298. """Base class for warnings about features which will be deprecated in the future.""")
  299. class W_EnvironmentError(W_StandardError):
  300. """Base class for I/O related errors."""
  301. def __init__(self, space):
  302. self.w_errno = space.w_None
  303. self.w_strerror = space.w_None
  304. self.w_filename = space.w_None
  305. W_BaseException.__init__(self, space)
  306. def descr_init(self, space, args_w):
  307. W_BaseException.descr_init(self, space, args_w)
  308. if 2 <= len(args_w) <= 3:
  309. self.w_errno = args_w[0]
  310. self.w_strerror = args_w[1]
  311. if len(args_w) == 3:
  312. self.w_filename = args_w[2]
  313. self.args_w = [args_w[0], args_w[1]]
  314. # since we rebind args_w, we need special reduce, grump
  315. def descr_reduce(self, space):
  316. if not space.is_w(self.w_filename, space.w_None):
  317. lst = [self.getclass(space), space.newtuple(
  318. self.args_w + [self.w_filename])]
  319. else:
  320. lst = [self.getclass(space), space.newtuple(self.args_w)]
  321. if self.w_dict is not None and space.is_true(self.w_dict):
  322. lst = lst + [self.w_dict]
  323. return space.newtuple(lst)
  324. def descr_str(self, space):
  325. if (not space.is_w(self.w_errno, space.w_None) and
  326. not space.is_w(self.w_strerror, space.w_None)):
  327. errno = space.str_w(space.str(self.w_errno))
  328. strerror = space.str_w(space.str(self.w_strerror))
  329. if not space.is_w(self.w_filename, space.w_None):
  330. return space.wrap("[Errno %s] %s: %s" % (
  331. errno,
  332. strerror,
  333. space.str_w(space.repr(self.w_filename))))
  334. return space.wrap("[Errno %s] %s" % (
  335. errno,
  336. strerror,
  337. ))
  338. return W_BaseException.descr_str(self, space)
  339. W_EnvironmentError.typedef = TypeDef(
  340. 'EnvironmentError',
  341. W_StandardError.typedef,
  342. __doc__ = W_EnvironmentError.__doc__,
  343. __module__ = 'exceptions',
  344. __new__ = _new(W_EnvironmentError),
  345. __reduce__ = interp2app(W_EnvironmentError.descr_reduce),
  346. __init__ = interp2app(W_EnvironmentError.descr_init),
  347. __str__ = interp2app(W_EnvironmentError.descr_str),
  348. errno = readwrite_attrproperty_w('w_errno', W_EnvironmentError),
  349. strerror = readwrite_attrproperty_w('w_strerror', W_EnvironmentError),
  350. filename = readwrite_attrproperty_w('w_filename', W_EnvironmentError),
  351. )
  352. W_OSError = _new_exception('OSError', W_EnvironmentError,
  353. """OS system call failed.""")
  354. class W_WindowsError(W_OSError):
  355. """MS-Windows OS system call failed."""
  356. def __init__(self, space):
  357. self.w_winerror = space.w_None
  358. W_OSError.__init__(self, space)
  359. def descr_init(self, space, args_w):
  360. # Set errno to the POSIX errno, and winerror to the Win32
  361. # error code.
  362. W_OSError.descr_init(self, space, args_w)
  363. try:
  364. errno = space.int_w(self.w_errno)
  365. except OperationError:
  366. errno = self._default_errno
  367. else:
  368. errno = self._winerror_to_errno.get(errno, self._default_errno)
  369. self.w_winerror = self.w_errno
  370. self.w_errno = space.wrap(errno)
  371. def descr_str(self, space):
  372. if (not space.is_w(self.w_winerror, space.w_None) and
  373. not space.is_w(self.w_strerror, space.w_None)):
  374. if not space.is_w(self.w_filename, space.w_None):
  375. return space.wrap("[Error %d] %s: %s" % (
  376. space.int_w(self.w_winerror),
  377. space.str_w(self.w_strerror),
  378. space.str_w(self.w_filename)))
  379. return space.wrap("[Error %d] %s" % (space.int_w(self.w_winerror),
  380. space.str_w(self.w_strerror)))
  381. return W_BaseException.descr_str(self, space)
  382. if hasattr(rwin32, 'build_winerror_to_errno'):
  383. _winerror_to_errno, _default_errno = rwin32.build_winerror_to_errno()
  384. else:
  385. _winerror_to_errno, _default_errno = {}, 22 # EINVAL
  386. W_WindowsError.typedef = TypeDef(
  387. "WindowsError",
  388. W_OSError.typedef,
  389. __doc__ = W_WindowsError.__doc__,
  390. __module__ = 'exceptions',
  391. __new__ = _new(W_WindowsError),
  392. __init__ = interp2app(W_WindowsError.descr_init),
  393. __str__ = interp2app(W_WindowsError.descr_str),
  394. winerror = readwrite_attrproperty_w('w_winerror', W_WindowsError),
  395. )
  396. W_BytesWarning = _new_exception('BytesWarning', W_Warning,
  397. """Mixing bytes and unicode""")
  398. W_DeprecationWarning = _new_exception('DeprecationWarning', W_Warning,
  399. """Base class for warnings about deprecated features.""")
  400. W_ArithmeticError = _new_exception('ArithmeticError', W_StandardError,
  401. """Base class for arithmetic errors.""")
  402. W_FloatingPointError = _new_exception('FloatingPointError', W_ArithmeticError,
  403. """Floating point operation failed.""")
  404. W_ReferenceError = _new_exception('ReferenceError', W_StandardError,
  405. """Weak ref proxy used after referent went away.""")
  406. W_NameError = _new_exception('NameError', W_StandardError,
  407. """Name not found globally.""")
  408. W_IOError = _new_exception('IOError', W_EnvironmentError,
  409. """I/O operation failed.""")
  410. class W_SyntaxError(W_StandardError):
  411. """Invalid syntax."""
  412. def __init__(self, space):
  413. self.w_filename = space.w_None
  414. self.w_lineno = space.w_None
  415. self.w_offset = space.w_None
  416. self.w_text = space.w_None
  417. self.w_msg = space.w_None
  418. self.w_print_file_and_line = space.w_None # what's that?
  419. self.w_lastlineno = space.w_None # this is a pypy extension
  420. W_BaseException.__init__(self, space)
  421. def descr_init(self, space, args_w):
  422. # that's not a self.w_message!!!
  423. if len(args_w) > 0:
  424. self.w_msg = args_w[0]
  425. if len(args_w) == 2:
  426. values_w = space.fixedview(args_w[1])
  427. if len(values_w) > 0: self.w_filename = values_w[0]
  428. if len(values_w) > 1: self.w_lineno = values_w[1]
  429. if len(values_w) > 2: self.w_offset = values_w[2]
  430. if len(values_w) > 3: self.w_text = values_w[3]
  431. if len(values_w) > 4:
  432. self.w_lastlineno = values_w[4] # PyPy extension
  433. # kill the extra items from args_w to prevent undesired effects
  434. args_w = args_w[:]
  435. args_w[1] = space.newtuple(values_w[:4])
  436. W_BaseException.descr_init(self, space, args_w)
  437. def descr_str(self, space):
  438. return space.appexec([self], """(self):
  439. if type(self.msg) is not str:
  440. return str(self.msg)
  441. lineno = None
  442. buffer = self.msg
  443. have_filename = type(self.filename) is str
  444. if type(self.lineno) is int:
  445. if (type(self.lastlineno) is int and
  446. self.lastlineno > self.lineno):
  447. lineno = 'lines %d-%d' % (self.lineno, self.lastlineno)
  448. else:
  449. lineno = 'line %d' % (self.lineno,)
  450. if have_filename:
  451. import os
  452. fname = os.path.basename(self.filename or "???")
  453. if lineno:
  454. buffer = "%s (%s, %s)" % (self.msg, fname, lineno)
  455. else:
  456. buffer ="%s (%s)" % (self.msg, fname)
  457. elif lineno:
  458. buffer = "%s (%s)" % (self.msg, lineno)
  459. return buffer
  460. """)
  461. def descr_repr(self, space):
  462. if (len(self.args_w) == 2
  463. and not space.is_w(self.w_lastlineno, space.w_None)
  464. and space.len_w(self.args_w[1]) == 4):
  465. # fake a 5-element tuple in the repr, suitable for calling
  466. # __init__ again
  467. values_w = space.fixedview(self.args_w[1])
  468. w_tuple = space.newtuple(values_w + [self.w_lastlineno])
  469. args_w = [self.args_w[0], w_tuple]
  470. args_repr = space.str_w(space.repr(space.newtuple(args_w)))
  471. clsname = self.getclass(space).getname(space)
  472. return space.wrap(clsname + args_repr)
  473. else:
  474. return W_StandardError.descr_repr(self, space)
  475. W_SyntaxError.typedef = TypeDef(
  476. 'SyntaxError',
  477. W_StandardError.typedef,
  478. __new__ = _new(W_SyntaxError),
  479. __init__ = interp2app(W_SyntaxError.descr_init),
  480. __str__ = interp2app(W_SyntaxError.descr_str),
  481. __repr__ = interp2app(W_SyntaxError.descr_repr),
  482. __doc__ = W_SyntaxError.__doc__,
  483. __module__ = 'exceptions',
  484. msg = readwrite_attrproperty_w('w_msg', W_SyntaxError),
  485. filename = readwrite_attrproperty_w('w_filename', W_SyntaxError),
  486. lineno = readwrite_attrproperty_w('w_lineno', W_SyntaxError),
  487. offset = readwrite_attrproperty_w('w_offset', W_SyntaxError),
  488. text = readwrite_attrproperty_w('w_text', W_SyntaxError),
  489. print_file_and_line = readwrite_attrproperty_w('w_print_file_and_line',
  490. W_SyntaxError),
  491. lastlineno = readwrite_attrproperty_w('w_lastlineno', W_SyntaxError),
  492. )
  493. W_FutureWarning = _new_exception('FutureWarning', W_Warning,
  494. """Base class for warnings about constructs that will change semantically in the future.""")
  495. class W_SystemExit(W_BaseException):
  496. """Request to exit from the interpreter."""
  497. def __init__(self, space):
  498. self.w_code = space.w_None
  499. W_BaseException.__init__(self, space)
  500. def descr_init(self, space, args_w):
  501. if len(args_w) == 1:
  502. self.w_code = args_w[0]
  503. elif len(args_w) > 1:
  504. self.w_code = space.newtuple(args_w)
  505. W_BaseException.descr_init(self, space, args_w)
  506. W_SystemExit.typedef = TypeDef(
  507. 'SystemExit',
  508. W_BaseException.typedef,
  509. __new__ = _new(W_SystemExit),
  510. __init__ = interp2app(W_SystemExit.descr_init),
  511. __doc__ = W_SystemExit.__doc__,
  512. __module__ = 'exceptions',
  513. code = readwrite_attrproperty_w('w_code', W_SystemExit)
  514. )
  515. W_EOFError = _new_exception('EOFError', W_StandardError,
  516. """Read beyond end of file.""")
  517. W_IndentationError = _new_exception('IndentationError', W_SyntaxError,
  518. """Improper indentation.""")
  519. W_TabError = _new_exception('TabError', W_IndentationError,
  520. """Improper mixture of spaces and tabs.""")
  521. W_ZeroDivisionError = _new_exception('ZeroDivisionError', W_ArithmeticError,
  522. """Second argument to a division or modulo operation was zero.""")
  523. W_SystemError = _new_exception('SystemError', W_StandardError,
  524. """Internal error in the Python interpreter.
  525. Please report this to the Python maintainer, along with the traceback,
  526. the Python version, and the hardware/OS platform and version.""")
  527. W_AssertionError = _new_exception('AssertionError', W_StandardError,
  528. """Assertion failed.""")
  529. class W_UnicodeDecodeError(W_UnicodeError):
  530. """Unicode decoding error."""
  531. w_encoding = None
  532. w_object = None
  533. w_start = None
  534. w_end = None
  535. w_reason = None
  536. def descr_init(self, space, w_encoding, w_object, w_start, w_end, w_reason):
  537. # typechecking
  538. space.realstr_w(w_encoding)
  539. space.realstr_w(w_object)
  540. space.int_w(w_start)
  541. space.int_w(w_end)
  542. space.realstr_w(w_reason)
  543. # assign attributes
  544. self.w_encoding = w_encoding
  545. self.w_object = w_object
  546. self.w_start = w_start
  547. self.w_end = w_end
  548. self.w_reason = w_reason
  549. W_BaseException.descr_init(self, space, [w_encoding, w_object,
  550. w_start, w_end, w_reason])
  551. def descr_str(self, space):
  552. return space.appexec([self], """(self):
  553. if self.end == self.start + 1:
  554. return "'%s' codec can't decode byte 0x%02x in position %d: %s"%(
  555. self.encoding,
  556. ord(self.object[self.start]), self.start, self.reason)
  557. return "'%s' codec can't decode bytes in position %d-%d: %s" % (
  558. self.encoding, self.start, self.end - 1, self.reason)
  559. """)
  560. W_UnicodeDecodeError.typedef = TypeDef(
  561. 'UnicodeDecodeError',
  562. W_UnicodeError.typedef,
  563. __doc__ = W_UnicodeDecodeError.__doc__,
  564. __module__ = 'exceptions',
  565. __new__ = _new(W_UnicodeDecodeError),
  566. __init__ = interp2app(W_UnicodeDecodeError.descr_init),
  567. __str__ = interp2app(W_UnicodeDecodeError.descr_str),
  568. encoding = readwrite_attrproperty_w('w_encoding', W_UnicodeDecodeError),
  569. object = readwrite_attrproperty_w('w_object', W_UnicodeDecodeError),
  570. start = readwrite_attrproperty_w('w_start', W_UnicodeDecodeError),
  571. end = readwrite_attrproperty_w('w_end', W_UnicodeDecodeError),
  572. reason = readwrite_attrproperty_w('w_reason', W_UnicodeDecodeError),
  573. )
  574. W_TypeError = _new_exception('TypeError', W_StandardError,
  575. """Inappropriate argument type.""")
  576. W_IndexError = _new_exception('IndexError', W_LookupError,
  577. """Sequence index out of range.""")
  578. W_RuntimeWarning = _new_exception('RuntimeWarning', W_Warning,
  579. """Base class for warnings about dubious runtime behavior.""")
  580. W_KeyboardInterrupt = _new_exception('KeyboardInterrupt', W_BaseException,
  581. """Program interrupted by user.""")
  582. W_UserWarning = _new_exception('UserWarning', W_Warning,
  583. """Base class for warnings generated by user code.""")
  584. W_SyntaxWarning = _new_exception('SyntaxWarning', W_Warning,
  585. """Base class for warnings about dubious syntax.""")
  586. W_UnicodeWarning = _new_exception('UnicodeWarning', W_Warning,
  587. """Base class for warnings about Unicode related problems, mostly
  588. related to conversion problems.""")
  589. W_ImportWarning = _new_exception('ImportWarning', W_Warning,
  590. """Base class for warnings about probable mistakes in module imports""")
  591. W_MemoryError = _new_exception('MemoryError', W_StandardError,
  592. """Out of memory.""")
  593. W_UnboundLocalError = _new_exception('UnboundLocalError', W_NameError,
  594. """Local name referenced but not bound to a value.""")
  595. W_NotImplementedError = _new_exception('NotImplementedError', W_RuntimeError,
  596. """Method or function hasn't been implemented yet.""")
  597. W_AttributeError = _new_exception('AttributeError', W_StandardError,
  598. """Attribute not found.""")
  599. W_OverflowError = _new_exception('OverflowError', W_ArithmeticError,
  600. """Result too large to be represented.""")
  601. class W_UnicodeEncodeError(W_UnicodeError):
  602. """Unicode encoding error."""
  603. w_encoding = None
  604. w_object = None
  605. w_start = None
  606. w_end = None
  607. w_reason = None
  608. def descr_init(self, space, w_encoding, w_object, w_start, w_end, w_reason):
  609. # typechecking
  610. space.realstr_w(w_encoding)
  611. space.realunicode_w(w_object)
  612. space.int_w(w_start)
  613. space.int_w(w_end)
  614. space.realstr_w(w_reason)
  615. # assign attributes
  616. self.w_encoding = w_encoding
  617. self.w_object = w_object
  618. self.w_start = w_start
  619. self.w_end = w_end
  620. self.w_reason = w_reason
  621. W_BaseException.descr_init(self, space, [w_encoding, w_object,
  622. w_start, w_end, w_reason])
  623. def descr_str(self, space):
  624. return space.appexec([self], r"""(self):
  625. if self.end == self.start + 1:
  626. badchar = ord(self.object[self.start])
  627. if badchar <= 0xff:
  628. return "'%s' codec can't encode character u'\\x%02x' in position %d: %s"%(
  629. self.encoding, badchar, self.start, self.reason)
  630. if badchar <= 0xffff:
  631. return "'%s' codec can't encode character u'\\u%04x' in position %d: %s"%(
  632. self.encoding, badchar, self.start, self.reason)
  633. return "'%s' codec can't encode character u'\\U%08x' in position %d: %s"%(
  634. self.encoding, badchar, self.start, self.reason)
  635. return "'%s' codec can't encode characters in position %d-%d: %s" % (
  636. self.encoding, self.start, self.end - 1, self.reason)
  637. """)
  638. W_UnicodeEncodeError.typedef = TypeDef(
  639. 'UnicodeEncodeError',
  640. W_UnicodeError.typedef,
  641. __doc__ = W_UnicodeEncodeError.__doc__,
  642. __module__ = 'exceptions',
  643. __new__ = _new(W_UnicodeEncodeError),
  644. __init__ = interp2app(W_UnicodeEncodeError.descr_init),
  645. __str__ = interp2app(W_UnicodeEncodeError.descr_str),
  646. encoding = readwrite_attrproperty_w('w_encoding', W_UnicodeEncodeError),
  647. object = readwrite_attrproperty_w('w_object', W_UnicodeEncodeError),
  648. start = readwrite_attrproperty_w('w_start', W_UnicodeEncodeError),
  649. end = readwrite_attrproperty_w('w_end', W_UnicodeEncodeError),
  650. reason = readwrite_attrproperty_w('w_reason', W_UnicodeEncodeError),
  651. )