39

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.

  • 1
    and yes, using a mapping dict is probably the proper way to go... – Antti Haapala Jul 31 '13 at 1:18
  • 1
    Thanks. I ended up refactoring 'cause I didn't want to use globals or use a mapping dict. – Chris McKinnel Jul 31 '13 at 2:00
57
0
import sys
getattr(sys.modules[__name__], "Foo")

# or 

globals()['Foo']
| improve this answer | |
  • Accepted this answer 'cause it covers both sys and globals methods. – Chris McKinnel Jul 31 '13 at 2:00
4
0

You can do it with help of sys module:

import sys

def str2Class(str):
    return getattr(sys.modules[__name__], str)
| improve this answer | |
3
0
globals()[class_name]

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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.