Suppongo che tu stia cercando una soluzione best-effort e stai bene se i risultati non voluti non funzionano correttamente.
Per il proprio caso d'uso particolare, è possibile utilizzare register a pickle handler per oggetti funzione. Basta renderlo un gestore fittizio che è abbastanza buono per i tuoi scopi best-effort. Creare un gestore per le funzioni è possibile, è piuttosto complicato. Per evitare di influire su altri codici che decapitano, è probabile che si desideri annullare la registrazione del gestore quando si esce dal codice di registrazione.
Ecco un esempio (senza cancellazione):
import cPickle
import copy_reg
from types import FunctionType
# data to pickle: note that o['x'] is a lambda and they
# aren't natively picklable (at this time)
o = {'x': lambda x: x, 'y': 1}
# shows that o is not natively picklable (because of
# o['x'])
try:
cPickle.dumps(o)
except TypeError:
print "not natively picklable"
else:
print "was pickled natively"
# create a mechanisms to turn unpickable functions int
# stub objects (the string "STUB" in this case)
def stub_pickler(obj):
return stub_unpickler,()
def stub_unpickler():
return "STUB"
copy_reg.pickle(
FunctionType,
stub_pickler, stub_unpickler)
# shows that o is now picklable but o['x'] is restored
# to the stub object instead of its original lambda
print cPickle.loads(cPickle.dumps(o))
Esso stampa:
not natively picklable
{'y': 1, 'x': 'STUB'}
fonte
2013-01-13 23:13:03
Uh, cattura l'eccezione sollevata? –
La cattura dell'eccezione non sarebbe d'aiuto in quanto il pickling fallirebbe invece di "saltare cose che non può gestire". – user4815162342