简体   繁体   中英

How to change global variables using globals() in python method?

If I have the following Python script foo.py :

def foo() :
  my_dict = {'A': 1, 'B': 2, 'C': 3}
  globals().update(my_dict)
  print(A)
  print(B)
  print(C)

foo()

I can type this in ipython :

run foo.py
=> 1
=> 2
=> 3
A
=> 1

However, If I remove the foo() at the bottom :

def foo() :
  my_dict = {'A': 1, 'B': 2, 'C': 3}
  globals().update(my_dict)
  print(A)
  print(B)
  print(C)

# no foo

And I type this in ipython :

run foo.py
foo()
=> 1
=> 2
=> 3
A
=> NameError: name 'A' is not defined

I get this error. Why is this the case?

IPython's %run defaults to running the file in a new namespace and then copying the results into your namespace.

When foo.py contains a foo() call, that creates A , B , and C variables in the new namespace that IPython then copies to your namespace.

When foo.py doesn't contain a foo() call, you can call foo() yourself, but foo is still using its original namespace for globals. Calling foo() creates A , B , and C variables in foo 's original namespace, too late for IPython to pick them up and copy them into your namespace.

You can use %run with the -i flag to run the file in your namespace directly, avoiding these issues.

You need to declare element_dict a global variable before assigning it. Once you have an assign statement anywhere within a function, the variable being assigned is declared on a local scope only, unless otherwise specified. In your case, element_dict is declared locally due to element_dict = read_mass_from_file() .

See the documentation for more details.

To actually reference the global variable:

def mass_mode() :
  '''
  Add element names and masses to the global variables.
  '''
  global element_dict
  element_dict = read_mass_from_file()

will update the element_dict from the global scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM