I have the following setup in one module:
class A(object):
# stuff
class B(object):
# stuff
Now what I want to do is, creating an instance of class A by name (I just have the class name as a string) inside of B. How can I do this avoiding the globals function?
Why not just use A? Or do you have just a string 'A'? If yes, globals()['A'] is the way to go. The alternative would be getattr(sys.modules[__name__], 'A') but obviously globals() is more appropriate.
>>> dis.dis(lambda: getattr(sys.modules[__name__], 'Foo'))
1 0 LOAD_GLOBAL 0 (getattr)
3 LOAD_GLOBAL 1 (sys)
6 LOAD_ATTR 2 (modules)
9 LOAD_GLOBAL 3 (__name__)
12 BINARY_SUBSCR
13 LOAD_CONST 1 ('Foo')
16 CALL_FUNCTION 2
19 RETURN_VALUE
>>> dis.dis(lambda: globals()['Foo'])
1 0 LOAD_GLOBAL 0 (globals)
3 CALL_FUNCTION 0
6 LOAD_CONST 1 ('Foo')
9 BINARY_SUBSCR
10 RETURN_VALUE
>>> dis.dis(lambda: Foo)
1 0 LOAD_GLOBAL 0 (Foo)
3 RETURN_VALUE
So by just looking at the instructions used for the various ways to access Foo, using globals() is most likely faster than going through sys.modules.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With