Reason for globals() in Python?

前端 未结 8 864
北荒
北荒 2020-12-12 12:43

What is the reason of having globals() function in Python? It only returns dictionary of global variables, which are already global, so they can be used anywhere... I\'m ask

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 13:07

    globals() is useful for eval() -- if you want to evaluate some code that refers to variables in scope, those variables will either be in globals or locals.


    To expand a bit, the eval() builtin function will interpret a string of Python code given to it. The signature is: eval(codeString, globals, locals), and you would use it like so:

    def foo():
        x = 2
        y = eval("x + 1", globals(), locals())
        print("y=" + y) # should be 3
    

    This works, because the interpreter gets the value of x from the locals() dict of variables. You can of course supply your own dict of variables to eval.

提交回复
热议问题