Really dynamic Python command

Posted on 2009-12-27
Last Modified: 2012-05-08
Hello experts,

In Python, I have classes called A, B, ... X. I also have a string variable StringClassName which holds the name of the class I would like to create an instance of.

I don't want to have a million chained if sentences that each checks the content of StringClassName, I would much rather be able to somehow do new_class_instance = StringClassName(), which does not work since a string object is not callable.

If this is not possible, it would be great if you could tell me why.

I hope I am clear enough about my question.
Question by:mannsi
    LVL 9

    Accepted Solution


    simply use this:

    a = globals()['ClassName']
    instead of
    a = ClassName

    Author Comment

    Judging by the ugly syntax, I take it that this method is not widely used, right ? Do people simply use chained ifs ?
    LVL 41

    Expert Comment

    For a very small number of items, a nested if/then/else might be used.
    However, for any non-trivial number of classes, the syntax shown by zaghaghi is more concise, and accurate.

    Featured Post

    Enabling OSINT in Activity Based Intelligence

    Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

    Join & Write a Comment

    "The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
    Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
    Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
    Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now