Skip to content

Commit 8f8aeae

Browse files
committed
implement __getstate__ and __setstate__
1 parent a4d92af commit 8f8aeae

File tree

2 files changed

+58
-2
lines changed

2 files changed

+58
-2
lines changed

Diff for: qiskit/primitives/primitive_job.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,15 @@ def _submit(self):
4848
self._future = executor.submit(self._function, *self._args, **self._kwargs)
4949
executor.shutdown(wait=False)
5050

51-
def _prepare_dump(self):
52-
"""This method allows PrimitiveJob to be serialized"""
51+
def __getstate__(self):
5352
_ = self.result()
5453
_ = self.status()
54+
state = self.__dict__.copy()
55+
state["_future"] = None
56+
return state
57+
58+
def __setstate__(self, state):
59+
self.__dict__.update(state)
5560
self._future = None
5661

5762
def result(self) -> ResultT:

Diff for: test/python/primitives/test_primitive_job.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# This code is part of Qiskit.
2+
#
3+
# (C) Copyright IBM 2025.
4+
#
5+
# This code is licensed under the Apache License, Version 2.0. You may
6+
# obtain a copy of this license in the LICENSE.txt file in the root directory
7+
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8+
#
9+
# Any modifications or derivative works of this code must retain this
10+
# copyright notice, and modified files need to carry a notice indicating
11+
# that they have been altered from the originals.
12+
13+
"""Tests for PrimitiveJob."""
14+
15+
import pickle
16+
from test import QiskitTestCase
17+
18+
import numpy as np
19+
from ddt import data, ddt
20+
21+
from qiskit import QuantumCircuit
22+
from qiskit.primitives import PrimitiveJob, StatevectorSampler
23+
24+
25+
@ddt
26+
class TestPrimitiveJob(QiskitTestCase):
27+
"""Tests PrimitiveJob."""
28+
29+
@data(1, 2, 3)
30+
def test_serialize(self, size):
31+
"""Test serialize."""
32+
n = 2
33+
qc = QuantumCircuit(n)
34+
qc.h(range(n))
35+
qc.measure_all()
36+
sampler = StatevectorSampler()
37+
job = sampler.run([qc] * size)
38+
obj = pickle.dumps(job)
39+
job2 = pickle.loads(obj)
40+
self.assertIsInstance(job2, PrimitiveJob)
41+
self.assertEqual(job.job_id(), job2.job_id())
42+
self.assertEqual(job.status(), job2.status())
43+
self.assertEqual(job.metadata, job2.metadata)
44+
result = job.result()
45+
result2 = job2.result()
46+
self.assertEqual(result.metadata, result2.metadata)
47+
self.assertEqual(len(result), len(result2))
48+
for i in range(len(result)):
49+
self.assertEqual(result[i].metadata, result2[i].metadata)
50+
self.assertEqual(result[i].data.keys(), result2[i].data.keys())
51+
np.testing.assert_allclose(result[i].join_data().array, result2[i].join_data().array)

0 commit comments

Comments
 (0)