How to get class object from class name string in the same module?

Python

Python Problem Overview


I have a class

class Foo():
    def some_method():
        pass

And another class in the same module:

class Bar():
    def some_other_method():
        class_name = "Foo"
        # Can I access the class Foo above using the string "Foo"?

I want to be able to access the Foo class using the string "Foo".

I can do this if I'm in another module by using:

from project import foo_module
foo_class = getattr(foo_module, "Foo")

Can I do the same sort of thing in the same module?

The guys in IRC suggested I use a mapping dict that maps string class names to the classes, but I don't want to do that if there's an easier way.

Python Solutions


Solution 1 - Python

import sys
getattr(sys.modules[__name__], "Foo")

# or 

globals()['Foo']

Solution 2 - Python

You can do it with help of the sys module:

import sys

def str2Class(str):
    return getattr(sys.modules[__name__], str)

Solution 3 - Python

globals()[class_name]

Note that if this isn't strictly necessary, you may want to refactor your code to not use it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris McKinnelView Question on Stackoverflow
Solution 1 - PythonkhachikView Answer on Stackoverflow
Solution 2 - Pythonjh314View Answer on Stackoverflow
Solution 3 - Pythonuser2357112View Answer on Stackoverflow