私はあなたがベストエフォート型のソリューションを探していると仮定していますが、アンピリリングされた結果が正しく機能しない場合は問題ありません。
特定の使用例については、関数オブジェクトの場合はregister a pickle handlerが望ましい場合があります。ベストエフォートの目的のために十分なダミーのハンドラにしてください。関数のハンドラを作ることは可能ですが、ややこしいことです。 pickleの他のコードに影響を与えないようにするには、ロギングコードを終了するときにハンドラの登録を解除することをお勧めします。ここで
は、(任意の登録解除せず)の例です:
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))
それは出力します。また
not natively picklable
{'y': 1, 'x': 'STUB'}
育った例外をキャッチしますか? –
例外をキャッチすることは助けにはならないでしょう。 – user4815162342