3

I'm trying to find some info on reflection in python. I found a wikipedia article which gave this as a code snippet:

# without reflection
Foo().hello()

# with reflection
getattr(globals()['Foo'](), 'hello')()

I wasn't able to get this to work. What I really need is a way to just instantiate the object. So if I have a string 'Foo' I want to be able to get an object of type Foo. Like in java I could say something like: Class.forName("Foo")

Just found this...wonder why I couldn't find this before: Does python have an equivalent to Java Class.forName()?

Community
  • 1
  • 1
JPC
  • 8,096
  • 22
  • 77
  • 110

1 Answers1

12

What I really need is a way to just instantiate the object.

That's what the globals()['Foo']() part does.

And it works for me:

>>> class Foo:
...   def __init__(self): print "Created a Foo!"
...
>>> globals()['Foo']()
Created a Foo!
<__main__.Foo instance at 0x02A33350>
>>>
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • What is the difference between f = globals()['Foo']() and f = ['Foo']()? What does globals mean – JPC Jan 05 '11 at 07:09
  • 1
    @JPC, second is a syntax error. golbals() refer to the namespace of your module (which is a dictionary) and namespace is how Python deal with it's programs/modules. By golbals()['Foo'] you are accessing the key called 'Foo' in the glabals() dictionary. – Senthil Kumaran Jan 05 '11 at 07:15
  • 1
    That makes sense, thanks. Reflection in python is so much easier than in java! – JPC Jan 05 '11 at 07:21
  • `globals` is a function that returns a dict of the global variables. `globals()` calls that function, so now you have that dict. `globals()['Foo']` looks up the 'Foo' key in that dict, which gives you the value of the `Foo` global variable. – Karl Knechtel Jan 06 '11 at 00:04
  • 1
    Coming back to this years later in response to a random upvote: `['Foo']()` isn't actually a syntax error, but it will cause a `TypeError` at runtime. It means "make a list with one element in it, the string `'Foo'`, call that list, and let `f` be a name for the result of the call". It fails because lists are not callable. – Karl Knechtel May 28 '20 at 18:28