[Tutor] Inherit from SyntaxError?

Cameron Simpson cs at cskk.id.au
Sun Mar 19 18:06:00 EDT 2023


On 19Mar2023 10:30, Albert-Jan Roskam <sjeik_appie at hotmail.com> wrote:
>   I'm writing a parser using Beazly's PLY package. I defined a custom
>   exception (actually, two: one for the lexer and one for the parser). They
>   inherit from SyntaxError. Along with a few other exceptions (e.g.
>   MemoryError), I've always regarded SyntaxError as "special". Are there any
>   disadvantages to inheriting from SyntaxError? I could also inherit from
>   ValueError.

Sounds good to me. I've got a class which inherits from SyntaxError:

     class ParseError(SyntaxError):
       ''' A ParseError subclasses SyntaxError in order to change the initialiser.
           This object has an additional attribute .context for the relevant FileContext
           (which has a .parent attribute).
       '''

       def __init__(self, context, offset, message, *a):
         ''' Initialise a ParseError given a FileContext and the offset into `context.text`.
             Accept optional arguments `*a` after the `message`; if supplied these
             are embedded into `message` with %-formatting.
         '''
         if a:
           message = message % a
         self.msg = message
         self.filename = context.filename
         self.lineno = context.lineno
         self.text = context.text
         self.offset = offset
         self.context = context

I've had no problems, and it seems entirely sensible.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list