In the example below, I have placed the class Foo
inside its own module foo
.
Why is the external class dumped by ref? The instance ff
is not being dumped with its source code.
I am using Python 3.4.3 and dill-0.2.4.
import dill
import foo
class Foo:
y = 1
def bar( self, x ):
return x + y
f = Foo()
ff = foo.Foo()
print( dill.dumps( f, byref=False, recurse=True ) )
print( '\n' )
print( dill.dumps( ff, byref=False, recurse=True ) )
Well, the code above is actually wrong (should be Foo.y
, instead of y
). Correcting the code gives me an exception while dumping the f
instance.
I'm the
dill
author. Thefoo.Foo
instance (ff
) pickles by reference because it's defined in a file. This is primarily for compactness of the pickled string. So the primary issue I can think of when importing a class by reference is that the class definition is not found on the other resource you might want to unpickle to (i.e. no modulefoo
exists there). I believe that's a current feature request (and if it's not, feel free to submit a ticket on the github page).Note, however, if you do modify the class dynamically, it does pull in the dynamically modified code to the pickled string.
So when
Foo
is defined in__main__
,byref
is respected.However, when the class is defined in a module,
byref
is not respected.Note, that I wouldn't use the
recurse
option in this case, asFoo.y
will likely infinitely recurse. That's also something that I believe there's current ticket for, but if there isn't, there should be.Let's dig a little deeper… what if we modify the instance...
No biggie, it pulls in the dynamically added code. However, we'd probably like to modify
Foo
and not the instance.Ok, that's fine, but what about the
Foo
in our external module?Hmmm… not good. So the above is probably a pretty compelling use case to change the behavior
dill
exhibits for classes defined in modules -- or at least enable one of the settings to provide better behavior.In sum, the answer is: we didn't have a use case for it, so now that we do… this should be a feature request if it is not already.