Search code examples
pythongloballocals

Using globals() to create class object


I'm new in programming so please don't kill me for asking stupid questions. I've been trying to understand all that class business in Python and I got to the point where could not find answer for my question just by google it.

In my program I need to call a class from within other class based on string returned by function. I found two solutions: one by using getattr() and second one by using globals() / locals().

Decided to go for second solution and got it working but I'm really don't understand how it's working.

So there is the code example:

class Test(object):
    def __init__(self):
        print "WORKS!"

room = globals()['Test'] 
room()

type(room()) gives:

<class '__main__.Test'>

type(room) gives:

<type 'type'> # What????

It looks like room() is a class object, but shouldn't that be room instead of room()?

Please help me because it is a little bit silly if I write a code which I don't understand myself.


Solution

  • What happens here is the following:

    class Test(object):
        def __init__(self):
            print "WORKS!"
    
    room = globals()['Test']
    

    Here you got Test as room the way you wanted. Verify this:

    room is Test
    

    should give True.

    type(room()) gives:

    <class '__main__.Test'>
    

    You do one step an go it backwards: room() returns the same as Test() would - an instance of that class. type() "undoes" this step resp. gets the type of the object - this is, of course, Test.

    type(room) gives:

    <type 'type'> # What????
    

    Of course - it is the type of a (new style) class. The same as type(Test).


    Be aware, however, that for

    In my program I need to call a class from within other class based on string returned by function. I found two solutions: one by using getattr() and second one by using globals() / locals().

    it could be better to create an explicitly separate dict. Here you have full control over which objects/classes/... are allowed in that context and which are not.