Changes between Version 1 and Version 2 of Ticket #11577


Ignore:
Timestamp:
07/05/11 15:13:39 (8 years ago)
Author:
leif
Comment:

Legend:

Unmodified
Added
Removed
Modified
  • Ticket #11577

    • Property Owner changed from ncalexan to was
    • Property Component changed from sage-mode to pickling
  • Ticket #11577 – Description

    v1 v2  
    1 (The summary actually is not completely accurate - there might be some Python object this works for that I'm not aware of)
     1(The summary actually is not completely accurate - there might be some Python object this works for that I'm not aware of.)
    22
    3 If the filename passed to save() contains a dot, save() assumes that the user doesnt just want to dump the (pickled) object, but instead wants to call the object's save() method. I guess this makes sense in situations like save(g, 'mygraph.png'), but the code should fall back to dumping the pickled version (e.g. via try: ... except AttributeError: ... - suggested via IRC by leif) if the object has no save() method.
     3If the filename passed to `save()` contains a dot, `save()` assumes that the user doesn't just want to dump the (pickled) object, but instead wants to call the object's `save()` method. I guess this makes sense in situations like `save(g, 'mygraph.png')`, but the code should fall back to dumping the pickled version (e.g. via `try: ... except AttributeError: ...` - suggested via IRC by leif) if the object has no `save()` method.
    44
    5 leif also suggested checking if the file name extension is known - however I guess that we then should verify this with the object itself (e.g. it wouldn't make sense to save a graphics object to a .wav file) and not statically compare with a list of known extensions.
     5leif also suggested checking if the file name extension is known - however I guess that we then should verify this with the object itself (e.g. it wouldn't make sense to save a graphics object to a `.wav` file) and not statically compare with a list of known extensions.
    66
    77
     
    1919AttributeError: 'tuple' object has no attribute 'save'
    2020}}}
     21
     22Here's the culprit:
     23{{{
     24#!python
     25    # Add '.sobj' if the filename currently has no extension
     26    if os.path.splitext(filename)[1] == '':
     27        filename += '.sobj'
     28
     29    if filename.endswith('.sobj'):
     30        try:
     31            obj.save(filename=filename, compress=compress, **kwds)
     32        except (AttributeError, RuntimeError, TypeError):
     33            s = cPickle.dumps(obj, protocol=2)
     34            if compress:
     35                s = comp.compress(s)
     36            open(process(filename), 'wb').write(s)
     37    else:
     38        # Saving an object to an image file.
     39        # XXX This of course fails for plain Python objects:
     40        obj.save(filename, **kwds)
     41}}}