Home > Enterprise >  Is there a way to pickle a PriorityQueue?
Is there a way to pickle a PriorityQueue?

Time:06-16

This is Python 3.10. I use a PriorityQueue as a way to track Actors' turn order in my game. It's just a simple roguelike. I don't use the synchronization features of the PriorityQueue. My code:

import pickle
from queue import PriorityQueue

class GameEngine():
    def __init__(self):
        self.pqueue = PriorityQueue()

    def save_to_file(self):
        with open('save.pkl', 'wb') as file:
            pickle.dump(self, file, pickle.HIGHEST_PROTOCOL)

class Monster():
    pass

engine = GameEngine()
orc1 = Monster()
orc2 = Monster()

engine.pqueue.put((20,orc1))
engine.pqueue.put((10,orc2))

engine.save_to_file()

It returns TypeError: cannot pickle '_thread.lock' object. From what I understand PriorityQueue is not pickle-able. I've read here that Queue.Queue has a pickle-able alternative of collections.deque if the synchronization stuff is not necessary. Is there such an alternative to PriorityQueue, or is there a way to pickle it anyway? Other than implementing my own simplified version of PriorityQueue?

CodePudding user response:

As you don't need the synchronisation features of PriorityQueue, just use the light-weight heapq module. It provides functions (not methods) to work on a plain list:

import pickle
from heapq import heappush, heappop

class GameEngine():
    def __init__(self):
        self.pqueue = []

    def save_to_file(self):
        with open('save.pkl', 'wb') as file:
            pickle.dump(self, file, pickle.HIGHEST_PROTOCOL)

class Monster():
    pass

engine = GameEngine()
orc1 = Monster()
orc2 = Monster()

heappush(engine.pqueue, (20,orc1))
heappush(engine.pqueue, (10,orc2))

engine.save_to_file()
  • Related