Skip to content

Instantly share code, notes, and snippets.

@sobolevnrm
Created November 24, 2015 18:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sobolevnrm/dd72550b571339e16997 to your computer and use it in GitHub Desktop.
Save sobolevnrm/dd72550b571339e16997 to your computer and use it in GitHub Desktop.
I am trying to create the object of a class when I have only the string of the class name avoiding a bunch of conditionals
# I have lots of classes with very similar constructors. I'd like to avoid a huge if elseif ... statement
# This works when all classes are specified in the global scope but breaks across modules -- it also doesn't seem very safe
class Foo:
def __init__(self):
self.bar = "FOOBAR"
class_name = "Foo"
ctor = globals()[class_name]
obj = ctor()
print(obj.bar)
@keith923
Copy link

Here's a solution that fits your example, where the class is defined in the same file in which it's used:

class Foo:
    def __init__(self):
        self.bar = "FOOBAR"

def test():
    # NB: This only works if the class is defined in the same file/module!
    module = __import__(__name__)

    class_name = "Foo"
    ctor = getattr(module, class_name)
    obj = ctor()
    print(obj.bar)

if __name__ == "__main__":
    test()

This SO answer will prove helpful should you want to know more about how this works, or decide that you want to access your class from a different file/module.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment