python3: convert string to type
Question: I have a set of classes `A`, `B`, `C` in a "front end" package `p1`. They all
inherit from `p1.X`.

I have another set of classes `A`, `B`, `C` in a "back end" package `p2`. They
all inherit from `p2.Y`.

In `p1.X`, I set one backend, so that `p1.A` uses `p2.A` as backend, `p1.B`
uses `p2.B`, etc. This mapping is done based on the class name in an inherited
method.

Now, I suceed to have, for example, `backend = "p2.A"` (string), but when I
try to eval this, python doesn't knows about `p2`, even if this is imported
earlier.

What did I do wrong? Should I import inside the eval? Should like spaghetti
code... Do you have a better idea?

Thanks.

P.S.: I currently have something like this in the "parent" `p1.X` class, which
is awful, but good to clarify what I want:

    
    
    def getBackendClass(self):
        myClass = ... # (class without package name)
        if myClass == "A":
               return p2.A
        elif myClass == "B":
               return p2.B
        ...
    


Answer: Little hacky solution, but should work, and is not hardcoded.

p2.py:

    
    
    class Y(object):
        @classmethod
        def fromString(cls, s):
            cls_name = s.split(".")[1]
            for c in cls.__subclasses__():
                if c.__name__() == cls_name:
                    return c()
            raise ValueError("%s not found in subclasses" % s)
    

