1

According to this post:

Python memoising/deferred lookup property decorator

A mnemonic decorator can be used to declare a lazy property in a class. There is even an 'official' package that can be used out of the box:

https://pypi.python.org/pypi/lazy

however, both of these implementation has a severe problem: any memorized values will be attempted to be pickled by python. If these values are unpicklable it will cause the program to break down.

My question is: is there an easy way to implement scala's "@transient lazy val" declaration without too much tinkering? This declaration should remember the property in case of multiple invocation, and drop it once the class/object is serialized.

Community
  • 1
  • 1
tribbloid
  • 4,026
  • 14
  • 64
  • 103

1 Answers1

1

Unaware of scala implementation details, but the easiest solution comes to my mind, if you're satisfied with other aspects of the 'lazy property' library you've found, would be implementing __getstate__ and __setstate__ object methods, as described in Pickling and unpickling normal class instances

These methods are called by pickle/unpickle handler during object instance (de)serialization.

This way you can have fine-grained control of how/which attributes of your object serialized. You should read corresponding documentation on another two pickle-related methods as well (take care of __getinitargs__ specifically). Python deserialized objects initialization differes from common __new__ & __init__ sequence

agg3l
  • 1,444
  • 15
  • 21
  • I thought of it, but I cannot find any __getstate__ implementation in the superclass as a point of reference, plus, the point of decorator is simplicity, if the decorator cannot affect pickling composition on its own, then I don't think its a very convenient decorator. – tribbloid Oct 12 '16 at 23:12
  • as Python pickle documentation states: `If there is no __getstate__() method, the instance’s __dict__ is pickled`. So you can simply pickle/unpickle superclass `__dict__` yourself. Ability to handle such properties only with decorators... Hmm, I'm not sure of it – agg3l Oct 12 '16 at 23:16