78

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Chris McKinnel
  • 14,694
  • 6
  • 64
  • 67

3 Answers3

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

# or 

globals()['Foo']
khachik
  • 28,112
  • 9
  • 59
  • 94
  • Accepted this answer 'cause it covers both `sys` and `globals` methods. – Chris McKinnel Jul 31 '13 at 02:00
  • I know this is an old answer, but while a good answer it could be further improved by mentioning the pros/cons of the two options and which option is considered more pythonic. – dsollen Nov 29 '22 at 15:57
10

You can do it with help of the sys module:

import sys

def str2Class(str):
    return getattr(sys.modules[__name__], str)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jh314
  • 27,144
  • 16
  • 62
  • 82
8
globals()[class_name]

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

user2357112
  • 260,549
  • 28
  • 431
  • 505