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
Your example indicates that the module name
MBObjectdoesn’t need to be accessed dynamically, only the object inside. In that case, you can just doEdit: One problem is that you are giving your module and class the same name, which makes it difficult to distinguish them in your code. You’re getting confused between classes and modules. You have two things called MBObject. One is a module, the other is a class inside that module. When you do
from MBObject import MBObject, you import the class, but give yourself no reference to the module, making it awkward to subsequently import a second class (MBSquartObject) from the same module.You can get the effect you want by using the code I gave above, but you must not do
from MBObject import MBObject— when you do that, you don’t give yourself a reference to the module, only the class in that module. Instead, just doimport MBObjectand then access the MBObject class viaMBObject.MBObject.If you want to be able to refer to both the MBObject class and other classes from the same module without prefixing them with the module name, give the module a different name. Python style guidelines advise naming modules in all lowercase and classes in MixedCase. So name your module mbobject.py. Then you can do:
In general it is not a good idea in Python to give the same name to a module and a class. Modules and classes are different things, and giving them the same name can lead to confusions like this where you’re not clear on whether you’re dealing with the module or the class.