0

I have an application where I'd like to make the first instance of a class available for access by all subsequent instances of that class. I implemented this like:

class Basic(object):
    def __init__(self, initial=False):
        super(Basic, self).__init__()
        if initial:
            Basic.initial = self

It works nicely, but when I try to serialize it with pickle or dill, the dynamically created class attribute Basic.initial does not serialize properly (How to write all class variables to disk with dill?).

I've been told that what I'm doing is "bad" and I can understand that because it does seem kinda roundabout.

I want that first instance to be available for use in all future instances without passing it around constantly.

Is there a better way to accomplish this? Maybe one that will serialize properly?

Community
  • 1
  • 1
Chebyshev
  • 61
  • 5
  • Possible duplicate of [Creating a singleton in Python](http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python) – juanpa.arrivillaga Mar 13 '17 at 18:13
  • Maybe it isn't a dupe... but I believe if you go with the metaclass approach it will fix your pickle issue. But my advice is not to use singletons, just use a module. – juanpa.arrivillaga Mar 13 '17 at 18:15
  • I tried doing a metaclass and any class attribute created with `__call__` had the same serialization problem. Also I couldn't figure out how to store the instance of the class instead of the class object itself using a metaclass. – Chebyshev Mar 13 '17 at 18:21
  • Well, the good news is you probably just want to use a module, and ditch the class anyway. – juanpa.arrivillaga Mar 13 '17 at 18:22

1 Answers1

0

I ended up making a module that is something like this:

class BasicInit(object):
    def __init__(self):
        super(BasicInit, self).__init__()

    def read(self):
        #read some stuff from files...

    def work(self):
        #do whatever work

initial_thing = BasicInit()
initial_thing.read()

class Basic(BasicInit):
    initial = initial_thing
    def __init__(self):
        super(Basic, self).__init__()

And while that again seems roundabout, it seems to work.

Maybe there's a more elegant solution?

Chebyshev
  • 61
  • 5