← 输入框|github.com|刷新
Skip to content

Fix exception pickling: Move initial args assignment to BaseException.__new__ #44791

Closed

Description

@zseil
mannequin
BPO 1692335
Nosy @gvanrossum, @loewis, @brettcannon, @birkenfeld, @facundobatista, @jaraco, @abalkin, @pitrou, @vstinner, @taleinat, @avassalotti, @benjaminp, @orivej, @ambv, @slallum
Files
  • exc_args.diff: patch against trunk revision 54643
  • exc_args_25.diff: patch against release25-maint branch revision 54643
  • test_exception_pickle.py: failing test
  • exception-pickling.diff: patch by Georg
  • exception-pickling.diff: patch by Georg
  • exception_pickling_25.diff: getstate() patch for the 2.5 branch
  • exception_pickling_26.diff: getstate() patch for the 2.6 branch
  • exception_pickling_26.diff: fixed rejects and fuzz on the current svn version
  • issue1692335-tests.patch: Patch demonstrating the bug
  • init_args.patch
  • init_args.patch
  • 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 2012-07-29.12:24:55.210>
    created_at = <Date 2007-04-01.13:46:15.000>
    labels = ['interpreter-core', 'type-bug']
    title = 'Fix exception pickling: Move initial args assignment to BaseException.__new__'
    updated_at = <Date 2018-10-11.14:43:02.459>
    user = 'https://bugs.python.org/zseil'

    bugs.python.org fields:

    activity = <Date 2018-10-11.14:43:02.459>
    actor = 'orivej'
    assignee = 'sbt'
    closed = True
    closed_date = <Date 2012-07-29.12:24:55.210>
    closer = 'sbt'
    components = ['Interpreter Core']
    creation = <Date 2007-04-01.13:46:15.000>
    creator = 'zseil'
    dependencies = []
    files = ['7915', '7916', '7917', '7918', '7919', '7920', '7921', '9198', '17509', '26537', '26550']
    hgrepos = []
    issue_num = 1692335
    keywords = ['patch']
    message_count = 64.0
    messages = ['52348', '52349', '52350', '52351', '52352', '52353', '52355', '52356', '52357', '52359', '52360', '52361', '52362', '52363', '55165', '55958', '56054', '60067', '60163', '61967', '61997', '61999', '62025', '70453', '75955', '76020', '76026', '76028', '102995', '106811', '108954', '108960', '117139', '117145', '117149', '133581', '151039', '151068', '166332', '166477', '166523', '166526', '166527', '166552', '166555', '166557', '166558', '166572', '166581', '166590', '166592', '166598', '166601', '166605', '166640', '166665', '166717', '166750', '166791', '183153', '310939', '310951', '310955', '310958']
    nosy_count = 27.0
    nosy_names = ['gvanrossum', 'loewis', 'nnorwitz', 'brett.cannon', 'georg.brandl', 'facundobatista', 'jafo', 'ehuss', 'tseaver', 'jaraco', 'belopolsky', 'zseil', 'fmitha', 'pitrou', 'vstinner', 'taleinat', 'alexandre.vassalotti', 'benjamin.peterson', 'jarpa', 'bpb', 'orivej', 'zbysz', 'kylev', 'lukasz.langa', 'python-dev', 'sbt', 'slallum']
    pr_nums = []
    priority = 'critical'
    resolution = 'fixed'
    stage = 'commit review'
    status = 'closed'
    superseder = None
    type = 'behavior'
    url = 'https://bugs.python.org/issue1692335'
    versions = ['Python 2.7']

    Activity

    1. zseil commented on Apr 1, 2007

      zseilmannequin
      MannequinAuthor

      Pickling exceptions fails when an Exception class
      requires an argument in the constructor, but doesn't
      call its base class' constructor. See this mail
      for details:

      http://mail.python.org/pipermail/python-dev/2007-April/072416.html

      This patch simply moves initial args assignment to
      BaseException.__new__. This should fix most of the
      problems, because it is very unlikely that an
      exception overwrites the __new__ method; exceptions
      used to be old style classes, which don't support
      the __new__ special method.

      The args attribute is still overwritten in all the
      __init__ methods, so there shouldn't be any backward
      compatibility problems.

    2. added
      interpreter-core
      on Apr 1, 2007
    3. zseil commented on Apr 1, 2007

      zseilmannequin
      MannequinAuthor

      File Added: exc_args_25.diff

    4. zseil commented on Apr 1, 2007

      zseilmannequin
      MannequinAuthor

      I'm attaching a test that Eric Huss sent in private
      mail.

      The test fails, because old exception pickles don't
      have args for the reconstructor, but their __init__()
      gets called anyway because they are new style classes
      now.

      The problem is in cPickle.InstanceNew() and
      pickle.Unpickler._instantiate(). Those methods behave
      differently depending on the type of the object
      instantiated; they avoid the __init__() call when type
      is an old style class.

      There is nothing that can be done in the exception
      classes to fix this issue; the fix would need to be
      in the pickle and cPickle module.
      File Added: test_exception_pickle.py

    5. ehuss commented on Jun 15, 2007

      ehussmannequin
      Mannequin

      I have stumbled across another scenario where unpickling fails. If your exception takes arguments, but you call Exception.__init__ with a different number of arguments, it will fail. As in:

      class D(Exception):
          def __init__(self, foo):
              self.foo = foo
              Exception.__init__(self)
    6. ehuss commented on Jun 27, 2007

      ehussmannequin
      Mannequin

      Added patch bpo-1744398 as an alternate solution.

    7. birkenfeld commented on Aug 11, 2007

      @birkenfeld
      Member

      Attaching a new patch that fixes the

      class D(Exception):
          def __init__(self, foo):
              self.foo = foo
              Exception.__init__(self)

      scenario by keeping the original args to __new__ as an exception attribute.
      File Added: exception-pickling.diff

    8. nnorwitz commented on Aug 11, 2007

      nnorwitzmannequin
      Mannequin

      self->args needs to be initialized to NULL because if the alloc of args failed, self->args would be uninitialized and deallocated. (I realize the alloc of an empty tuple will realistically never fail currently.)

      I'm not sure if this could cause any new problems because of the behavior change, but the code itself looked fine to me. Hopefully someone with more knowledge of exceptions could take a look at the idea.

    9. ehuss commented on Aug 12, 2007

      ehussmannequin
      Mannequin

      Georg's new patch looks good to me, it seems to pass all the scenarios that I know of. You can close out my patch if you check this in. Thanks for looking into this!

    10. birkenfeld commented on Aug 12, 2007

      @birkenfeld
      Member

      The only question left is what to do if something reassigns exceptioninstance.args.

    11. zseil commented on Aug 12, 2007

      zseilmannequin
      MannequinAuthor

      There is also the problem that Jim Fulton mentioned
      in bug bpo-1742889; if the user modifies the 'message'
      attribute of an exception (or any other attribute
      that is not stored in the __dict__), it won't get
      serialized on pickling.

      Attaching a new patch that fixes this by using the
      __getstate__() pickling hook. It uses tp_members
      and tp_getset members of the type object to find
      all the attributes that need to be serialized.

      The 2.5 patch also contains a fix for migrating
      old exception pickles to Python 2.5. For that
      I had to change cPickle and pickle. It would
      be nice if Jim could comment if this change is
      needed, since ZODB is probably the biggest user
      of these modules.

      The downside is that this patch is fairly big.

      File Added: exception_pickling_25.diff

    12. zseil commented on Aug 12, 2007

      zseilmannequin
      MannequinAuthor

      File Added: exception_pickling_26.diff

    13. birkenfeld commented on Aug 12, 2007

      @birkenfeld
      Member

      I wouldn't care too much about .message; it was new in 2.5 and is already deprecated in 2.6.

    14. zseil commented on Aug 12, 2007

      zseilmannequin
      MannequinAuthor

      It's not just the message attribute; the problem is
      that the current code expects that the exception
      won't be modified between creation and unpickling.

      For example:

      >>> import pickle
      >>> e = EnvironmentError()
      >>> e.filename = "x"
      >>> new = pickle.dumps(pickle.loads(e))
      >>> print new.filename
      None
      >>> e = SyntaxError()
      >>> e.lineno = 10
      >>> new = pickle.loads(pickle.dumps(e))
      >>> print new.lineno
      None
    15. 64 remaining items

    16. sbt commented on Jul 29, 2012

      sbtmannequin
      Mannequin

      Richard, can the issue be closed?

      I guess so (although the change could arguably be back ported).

      Pickling of Exception classes is still somewhat dodgy because an example like

          class Error(Exception):
              def __init__(self, x):
                  Exception.__init__(self)
                  self.x = x

      is still not picklable.

      Any further improvements can be discussed in a separate issue, so I will close.

    17. birkenfeld commented on Jul 29, 2012

      @birkenfeld
      Member

      Please reopen if you think it should be backported.

    18. python-dev commented on Feb 27, 2013

      python-devmannequin
      Mannequin

      New changeset 2c9f7ed28384 by R David Murray in branch '3.2':
      bpo-17296: backport fix for bpo-1692335, naive exception pickling.
      http://hg.python.org/cpython/rev/2c9f7ed28384

      New changeset 67c27421b00b by R David Murray in branch '3.3':
      Null merge for bpo-1692335 backport.
      http://hg.python.org/cpython/rev/67c27421b00b

      New changeset 94f107752e83 by R David Murray in branch 'default':
      Null merge for bpo-1692335 backport.
      http://hg.python.org/cpython/rev/94f107752e83

    19. slallum commented on Jan 28, 2018

      slallummannequin
      Mannequin

      Perhaps this is a problem for a different issue, but pickling custom exceptions fails when the exception gets more than one argument:

      import pickle
      class MultipleArgumentsError(Exception):
          def __init__(self, a, b):
              self.a = a
              self.b = b
              Exception.__init__(self, a)
      
      pickle.loads(pickle.dumps(MultipleArgumentsError('a', 'b')))

      this code produces the following error:

      Traceback (most recent call last):
        File "/tmp/multiple_arguments_exception.py", line 8, in <module>
          pickle.loads(pickle.dumps(MultipleArgumentsError('a', 'b')))
        File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1388, in loads
          return Unpickler(file).load()
        File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 864, in load
          dispatch[key](self)
        File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1139, in load_reduce
          value = func(*args)
      TypeError: __init__() takes exactly 3 arguments (2 given)
    20. jaraco commented on Jan 28, 2018

      @jaraco
      Member

      @slallum, That does seem to be a problem, though I do observe that the issue reported by bdb with CalledProcessError is no longer an issue:

      >>> import subprocess, pickle
      >>> try:
      ...   subprocess.check_call(['python', '-c', 'raise SystemExit(1)'])
      ... except Exception as e:
      ...   pickle.loads(pickle.dumps(e))
      ... 
      CalledProcessError(1, ['python', '-c', 'raise SystemExit(1)'])

      Looking into how CalledProcessError is defined (

      class CalledProcessError(SubprocessError):
      ) may shed some light on the recommended way to make a pickleable Exception class that takes more than one argument.

      Hmm. It seems it does it by not calling the superclass __init__. Indeed, following that model it seems to work:

      import pickle
      class MultipleArgumentsError(Exception):
          def __init__(self, a, b):
              self.a = a
              self.b = b
      
      err = pickle.loads(pickle.dumps(MultipleArgumentsError('a', 'b')))
      assert err.a == 'a'
      assert err.b == 'b'
    21. slallum commented on Jan 28, 2018

      slallummannequin
      Mannequin

      @jason.coombs as far as I can tell, this only works in python3, but not in python2, where it still produces the same error.

    22. gvanrossum commented on Jan 28, 2018

      @gvanrossum
      Member

      Please don't discuss on closed issues. Open a new issue.

    23. 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