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()?

1
  • you are almost there: fooobj = globals()['Foo']() ... fooobj.hello() Commented Jan 5, 2011 at 7:13

1 Answer 1

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>
>>>
Sign up to request clarification or add additional context in comments.

5 Comments

What is the difference between f = globals()['Foo']() and f = ['Foo']()? What does globals mean
@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.
That makes sense, thanks. Reflection in python is so much easier than in java!
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.