I have a string type with a value of "MBSquareObject". MBSquareObject is class in a file called MBObject. I want to import MBSquareObject dynamically.
If the square object was in a file of its own, this works:
__import__(type)
However, what I want to do is the equivalent of from MBObject import MBSquareObject. However, this doesn't work:
from MBObject __import__(type)
How else could I do this?
Edit: the answers given are assuming that MBSquareObject is some sort of object on MBObject, but it's just another class. MBSquareObject is a subclass of MBObject, so they are listed in the same file.
Edit: for some reason none of the answers are working. Here's what I have:
# this is imported at the top of the file
from MBObject import MBObject
type = 'MBSquareObject'
__import__('MBObject', globals(), locals(), [type])
object_class = eval(type)
object = object_class()
Error: NameError: name 'MBSquareObject' is not defined