[Python] Some precautions when using exec

[Do not reprint without my consent]
[This article was published on CSDN, the address is: https://blog.csdn.net/weixin_44733774/article/details/124692142



The book inherits some details of globals and locals above, but the content of this article is not very related to globals() and locals().

The code that appears in the blog is passed to gayhub: https://github.com/Ls-Jan/Python_LanguageFeatures/tree/main/exec





二、exec()

Learn to be good, learn to be good, and dare not be reckless after being scared by the locals() thing, first check the official description of exec(): exec(object[, globals[, locals]])
which mentions many The content is not very exhaustive, and they are listed here


1. If exec does not pass in a dictionary, it will pass in globals() and locals() by default

    




2. If exec passes in a dictionary, a dictionary will be used as a global and local variable

  That is, variables defined in exec will be saved into this dictionary.
  Add something useless: this dictionary will be added __builtins__
    




3. If exec passes in two dictionaries, these two dictionaries will be used as global variables and local variables in turn

  Exec can execute the code containing the word global, which is not contradictory. Please try the details yourself, I won’t introduce much here (mainly because I’m so tired...)
  Another point to add is, py “不是没有分号”, but “不建议使用分号”(because the use of semicolons will cause a decrease in readability
    




4. If exec is used in the function, it is recommended to pass in the specified dictionary for recording and using variables

  在第1点中已经提及了,exec如果不传字典的话会默认使用globals()和locals()的。
  Locals() is new every time the function is called (this is normal, if it is not refreshed, the problem will be big), that is, the variables defined when you execute exec in the function will "disappear" in the next function call.
  Generally, if there is no special requirement, it is enough to pass in a dictionary. As for where this dictionary should be stored, it is a matter of opinion. It is recommended to store it in a class object
    





Digression:
The interpreter of exec is very good. The local variable dictionary passed into exec is strictly synchronized with the local variables of the interpreter.
That is, the local variables you pass into exec will be used honestly by the exec interpreter.
  







I thought that the blog post should be finished in less than one or two hours, but it turned out that most of the day passed. I can only say that the efficiency is touching.

Guess you like

Origin blog.csdn.net/weixin_44733774/article/details/124692142