Using pythons property while loading old objects

2024/9/8 10:43:53

I have a rather large project, including a class Foo which recently needed to be updated using the @property decorator to create custom getter and setter methods.

I also stored several instances of Foo on my hard drive that at some point I might need to reload. My problem is, that I cannot access the attributes decoreted with property on these old objects.

Consider the following example:

import pickle# define Class and create instance
class Foo:def __init__(self):self.val = 1
foo = Foo()# dump foo into file
with open("foo.pickle", 'wb') as handle:pickle.dump(foo, handle, pickle.HIGHEST_PROTOCOL)# overwrite and add @property in the class definition
class Foo:def __init__(self):self._val = "new_foo"@propertydef val(self):return self._val@val.setterdef val(self, val):self._val = valfoo_new = Foo()
print(foo_new.val)# reload foo
with open("foo.pickle", "rb") as handle:foo_old = pickle.load(handle)# try to access attributes
print(foo_old.val)

The last line raises:

NameError: name '_val' is not defined

What options do I have to still access the attributes of my archived instances?

Edit: Changed self.val to self._val in the constructor of the second Foo-definition.

Answer

The pickle documentation says:

When a class instance is unpickled, its __init__() method is usually not invoked.

Which is why the _val attribute wasn't defined You can workaround that by defining a __new__ method in the replacement Foo class and setting the instance attribute there:

import pickle# define Class and create instance
class Foo:def __init__(self):self.val = 1
foo = Foo()# dump foo into file
with open("foo.pickle", 'wb') as handle:pickle.dump(foo, handle, pickle.HIGHEST_PROTOCOL)# overwrite and add @property in the class definition
class Foo:def __new__(cls, val=None):inst = super().__new__(cls)inst._val = "new_foo"  if val is None else valreturn inst@propertydef val(self):return self._val@val.setterdef val(self, val):self._val = valfoo_new = Foo()
print(foo_new.val)  # -> new_foo# reload foo
with open("foo.pickle", "rb") as handle:foo_old = pickle.load(handle)print(foo_old.val)  # -> new_foo
https://en.xdnf.cn/q/72592.html

Related Q&A

How to replace all those Special Characters with white spaces in python?

How to replace all those special characters with white spaces in python ?I have a list of names of a company . . . Ex:-[myfiles.txt] MY company.INCOld Wine pvtmaster-minds ltd"apex-labs ltd"…

Python 3.x : move to next line

Ive got a small script that is extracting some text from a .html file.f = open(local_file,"r") for line in f:searchphrase = <span class="positionif searchphrase in line:print("fo…

Why couldnt Julia superset python?

The Julia Language syntax looks very similar to python, while the concept of a class (if one should address it as such a thing) is more what you use in C. There were many reasons why the creators decid…

How to log into Google Cloud Storage from a python function?

I am new to google cloud storage and I try to set up a function that downloads a blob once a day. At the moment I am working in my Jupyter Notebook but finally, the code will run in an Azure Function. …

OpenCV Python, reading video from named pipe

I am trying to achieve results as shown on the video (Method 3 using netcat)https://www.youtube.com/watch?v=sYGdge3T30oThe point is to stream video from raspberry pi to ubuntu PC and process it using …

Load model with ML.NET saved with keras

I have a Neural Network implemented in Python with Keras. Once I have trained it I have exported the model and I have got two files: model.js and model.h5. Now I want to classify in real time inside a …

unable to add spark to PYTHONPATH

I am struggling to add spark to my python path:(myenv)me@me /home/me$ set SPARK_HOME="/home/me/spark-1.2.1-bin-hadoop2.4" (myenv)me@me /home/me$ set PYTHONPATH=$PYTHONPATH:$SPARK_HOME:$SPARK_…

Is there a way to shallow copy an existing file-object?

The use case for this would be creating multiple generators based on some file-object without any of them trampling each others read state. Originally I (thought I) had a working implementation using s…

Python - Import package modules before as well as after setup.py install

Assume a Python package (e.g., MyPackage) that consists of several modules (e.g., MyModule1.py and MyModule2.py) and a set of unittests (e.g., in MyPackage_test.py).. ├── MyPackage │ ├── __ini…

Where can I find the _sre.py python built-in module? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…