Instantiate an object based on a variable name

Stephen Hansen apt.shansen at gmail.com
Thu Dec 31 12:06:03 EST 2009


On Thu, Dec 31, 2009 at 8:54 AM, Wells <thewellsoliver at gmail.com> wrote:

> Sorry, this is totally basic, but my Google-fu is failing:
>
> I have a variable foo. I want to instantiate a class based on its
> value- how can I do this?


It sort of depends on where these classes are. If they're in the current
namespace/module, something like:
    class A:
        pass

    class B:
        pass

    class C:
        pass

    my_variable = "B"
    instance = globals()[my_variable]()

Basically, globals() returns a dictionary of the current module's globals,
which you can access as you please. Personally, I find this ugly and
slightly dangerous(as who knows what else is in your globals that may get
accessed), and would prefer an explicit mapping of available-classes, e.g.:
    valid_classes = {"A": A, "B": B, "C": C}
    instance = valid_classes[my_variable]()


--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20091231/5a7ee6d2/attachment.html>


More information about the Python-list mailing list