python - Shadow a global variable with a modified copy -


Please note: this question about changing a global variable inside the function body is not . I understand the global keyword

My script has a bunch of global configuration variables that I want to type in a function that is shadowed by one of those global variables in the local namespace (below modified_procedure () And calls another function that refers to the configuration variable Ie,

  PARAMETER = 1 def process (): return parameter * 3 def modified_procedure (): parameter + = 1 Return Process ()  

This fails because parameters O is in the body of modified_procedure () , interpreter considers it a local variable and does not appear in the global namespace. I do not try to change the global variable PARAMETER I am trying to do cinematography in modified_procedure () namespace

I can think of some uncomfortable solutions:

    < Li> OOPify the script so that the configuration variables object attributes and Can I create a subclass with a new process ()
  • In global , modify the modified_procler () to Use to modify PARAMETER and then restore it before retrieving the result of the process ()

Do I call it Can I cover the PARAMETER ? if so, how?

Are you asking for amount for dynamic scoping Python, most of which still be used today Languages ​​(notable exceptions for being Pearl and Emacs Lisp), does not support dynamic skoping, choose Lexical Scropping.

You can change the process function to change its __global___ object. But it will hack even more, and more code to boot. If you can change the process to accept a parameter, do so. If the global should change temporarily, then it is going to be the least painful and surprising approach.


Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -