Using pickle for classes

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
Maksym Galemin
Posts: 11
Joined: Mon May 28, 2018 11:48 pm

Using pickle for classes

Post by Maksym Galemin » Fri Dec 21, 2018 2:56 am

I'm struggling to understand how I can pickle arbitrary classes in MicroPython. Currently uP pickle is implemented using repr() and it looks like in order for a class to be pickleable it has to implement __repr__() method with a specific output format (similar to creating an object of the class).

Is there a way to pickle an uasyncio.queues.Queue() object for example or to do something like from the example below?

Code: Select all

import pickle

class MyClass(object):
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

my_class = MyClass(100, 'Baaar')
print('Orig: %s' % my_class.__dict__)

with open('my_class.pkl', 'wb') as f:
    pickle.dump(my_class, f)

with open('my_class.pkl', 'rb') as f:
    my_class_1 = pickle.load(f)
    print('Unpickled: %s' % my_class_1.__dict__)
Pickleable version of the same class:

Code: Select all

class MyClass(object):
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

    def __repr__(self):
        return ('%s.%s(%s, %s)' % (self.__module__, self.__qualname__, self.foo, self.bar))

Post Reply