Skip to content

Exception ABC doesn't work in Python 3 (but does in Python 2.7) #69634

Closed

Description

@merchise
mannequin
BPO 25448
Nosy @rhettinger, @ncoghlan, @bitdancer, @eryksun, @MojoVampire
Superseder
  • bpo-12029: [doc] clarify that except does not match virtual subclasses of the specified exception type
  • Files
  • tests.py: A test command to reproduce the error.
  • Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

    Show more details

    GitHub fields:

    assignee = None
    closed_at = <Date 2015-10-21.02:32:09.832>
    created_at = <Date 2015-10-20.19:32:31.154>
    labels = ['interpreter-core', 'type-bug']
    title = "Exception ABC doesn't work in Python 3 (but does in Python 2.7)"
    updated_at = <Date 2015-10-21.02:32:09.831>
    user = 'https://bugs.python.org/merchise'

    bugs.python.org fields:

    activity = <Date 2015-10-21.02:32:09.831>
    actor = 'eryksun'
    assignee = 'none'
    closed = True
    closed_date = <Date 2015-10-21.02:32:09.832>
    closer = 'eryksun'
    components = ['Interpreter Core']
    creation = <Date 2015-10-20.19:32:31.154>
    creator = 'merchise'
    dependencies = []
    files = ['40823']
    hgrepos = []
    issue_num = 25448
    keywords = []
    message_count = 7.0
    messages = ['253246', '253253', '253258', '253268', '253269', '253271', '253273']
    nosy_count = 6.0
    nosy_names = ['rhettinger', 'ncoghlan', 'r.david.murray', 'eryksun', 'josh.r', 'merchise']
    pr_nums = []
    priority = 'normal'
    resolution = 'duplicate'
    stage = 'resolved'
    status = 'closed'
    superseder = '12029'
    type = 'behavior'
    url = 'https://bugs.python.org/issue25448'
    versions = ['Python 2.7', 'Python 3.4', 'Python 3.5', 'Python 3.6']

    Activity

    1. merchise commented on Oct 20, 2015

      merchisemannequin
      MannequinAuthor

      When I run the next code in all my installed versions of Python 3 (and the equivalent code for PyPy and CPython 2.7):

      • Runs OK in CPython 2.7 equivalent code (using ABCMeta as meta-class).

      • Fails in PyPy and all versions of Python 3.

    2. added
      type-bug
      on Oct 20, 2015
    3. bitdancer commented on Oct 20, 2015

      @bitdancer
      Member

      What are you trying to accomplish that needs an abstract base class?

      APIError is not an Exception class, it is a meta-class, and thus it does not match the exception because it is not a *base* class of DriverError (it is DiverError's *meta* class).

      Now, it is an interesting question whether we want the try/except statement's behavior to match issubclass, since intuitively we think the except in try except is doing the equivalent of issubclass (it isn't).

      I don't know why this works in python2, but the class/meta-class machinery did undergo some significant changes. So, it is possible that this is in fact a bug (ie: an unintentional change in semantics). If so, it is also a doc bug, since the try statement docs clear say the expression must evaluate to a base class, and the virtual class (abc) docs *only* mention issubclass and isinstance.

    4. bitdancer commented on Oct 20, 2015

      @bitdancer
      Member

      Thinking about this some more my explanation isn't quite clear (because my thinking wasn't quite clear): the problem isn't that APIError isn't *capable* of being a base class; I was wrong when I said it is itself a metaclass. It is a class that has ABCMeta *as* its metaclass. The problem is what I said in the second part: that APIError isn't a base class *of DriverError*. The operant issue is that 'except' isn't doing issubclass, it is looking at the base class list of DriverError, and APIError isn't in it.

      I'd have to see your 2.7 code to figure out why that version "works" :)

    5. eryksun commented on Oct 20, 2015

      @eryksun
      Contributor

      In Python 2, PyErr_GivenExceptionMatches 1 calls PyObject_IsSubclass. To handle calling __subclasscheck__ in this case, 2.7 (but not 2.6) temporarily increases the recursion limit by 5. For example:

          class CMeta(type):
              def __subclasscheck__(self, other):
                  import sys
                  print 'recursion limit: %d' % sys.getrecursionlimit()
                  frame = sys._getframe(1)
                  n = 0
                  while frame:
                      n += 1
                      frame = frame.f_back
                  print 'frame: %d' % n
                  return True
      
          class C(Exception):
              __metaclass__ = CMeta
      
          def f():
              try:
                  f()
              except C:
                  pass
          >>> sys.getrecursionlimit()
          1000
          >>> f()
          recursion limit: 1005
          frame: 1000
          >>> sys.getrecursionlimit()
          1000

      If the recursion limit weren't temporarily increased, then trying to call __subclasscheck__ in the above case would raise another RuntimeError.

      In Python 3, PyErr_GivenExceptionMatches 2 instead calls PyType_IsSubtype. See bpo-2534. In that issue Antoine's reason for the change is that "otherwise there are some nasty issues with recursion checking".

    6. added
      interpreter-core
      on Oct 20, 2015
    7. merchise commented on Oct 21, 2015

      merchisemannequin
      MannequinAuthor

      Thanks ~eryksun, you clarified me in where the error is located and possible patches for it.

      We are programming a framework where is very important to do mappings between (1) the API and (2) the drivers layers.

      We try to make our code available to both branches of Python (2 and 3). This case is complex because a logical exception type definition (like "resource not found") is implemented different by disparate API consumer applications (these implementing the drivers), for example httplib, couchdb or any specific database management system.

      So, the API layer have to find a way to uniform disparate exception "fauna" in its definitions at a logical level.

      ABCs are the nice solution, only have to work as its conceptual definition said, including exceptions, in all Python versions.

    8. MojoVampire commented on Oct 21, 2015

      MojoVampiremannequin
      Mannequin

      This looks like a duplicate of bpo-12029. The delays on addressing that bug seem to indicate that initially there was a fairly substantial performance cost for all exception handling paths when ABC friendly checking was performed, but that was at least partially due to a bug in those code paths that didn't bypass the ABC machinery in the simple subclass case.

      That said, I'm not sure it wouldn't cause other performance regressions (I made a comment to that effect on the original bug).

    9. merchise commented on Oct 21, 2015

      merchisemannequin
      MannequinAuthor

      Josh Rosenberg, you are right, it's a duplication. Sorry I didn't find the issue bpo-12029 before.

    10. transferred this issue fromon Apr 10, 2022
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Metadata

    Metadata

    Assignees

    No one assigned

      Labels

      interpreter-coretype-bug

      Projects

      No projects

        Milestone

        No milestone

        Relationships

        None yet

        Development

        No branches or pull requests

        Issue actions