0

I want to keep a dictionary of my custom classes so that I can dynamically instantiate them from other dictionaries (loaded from db), but I'm not sure what to store.

class_register = {}

class Foo(object):
    def __init__(self, **kwargs):
        class_register[self.__class__.__name__] = ??  # what to store here?
        self.__dict__.update(kwargs)

new_instance = class_register[result['class_name']](**result['data'])

Open to any suggestions.

2
  • Have you tried self.__class__? I'm not too sure why you'd need to do this. Can you explain your scenario a little more? Commented Dec 24, 2012 at 4:50
  • @Blender thanks for enquiring... I'm just converting MongoDB data into custom Python objects so I can get out of dict-land! Cheers. Commented Dec 24, 2012 at 5:06

2 Answers 2

2

Just store the class itself:

class_register[self.__class__.__name__] = self.__class__

But this is a bit of overkill, since you are registering the class every time you instantiate it.

Better is to use this:

def register(cls):
    class_register[cls.__name__] = cls

class Foo(object):
    # blah blah

register(Foo)

And then you can turn this into a class decorator to use like this:

def register(cls):
    class_register[cls.__name__] = cls
    return cls

@register
class Foo(object):
    # blah blah
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ned, I was really bothered by the fact I was registering every time I instantiated the class. The decorator solution is perfect. Merry Christmas!
2

I would inherit them off the same base class and then request __subclasses__() of that class, once I was sure they were all done. Perhaps in the form:

 Base.class_register = dict((x.__name__, x) for x in Base.__subclasses__())

It uses less magic to let Python do the bookkeeping.

Also, if they do not have enough in common to have this superclass seem warranted, you would probably have trouble using them in the same code after construction in any way that was not confusing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.