the global keyword:

BartC bc at freeuk.com
Tue Jun 21 19:15:49 EDT 2016


On 21/06/2016 23:20, Rick Johnson wrote:
> On Tuesday, June 21, 2016 at 12:15:38 PM UTC-5, Random832 wrote:

> Storing dynamic data to global space is almost always
> foolish, and I'm a fan of name spaces. But i did not
> recommend such foolish action, i was merely replying to the
> assertion that "Python does have real globals". She does,
> you just have look under the tail!

How would you use this idea to solve the OP's problem?

So, module M contains a top-variable G.

Module A imports M, and wants to access the identical variable G, 
without having to write it as M.G.

Assignments (not just in-place mods) to G in M will be reflected in A's 
G, and vice versa.

I tried using your method but it didn't work:

--------------------------------
M.py:
--------------------------------
  G = 5

  print ("M:G=",G)

  def F():
      global G
      G = 44
      print ("M.F:G=",G)
--------------------------------

--------------------------------
A.py (main module):
--------------------------------
import sys
sys.modules['__builtin__'].__dict__['G']=8888
import M

print ("G=",G)
M.F()
print ("G=",G)
--------------------------------

Output of running A.py:

('M:G=', 5)
('G=', 8888)
('M.F:G=', 44)
('G=', 8888)

Using A.G in A.py instead, I get the correct output (values of 5,5,44,44 
for G).


 > i was merely replying to the
 > assertion that "Python does have real globals". She does,
 > you just have look under the tail!

You shouldn't need to do that (what looks like abusing the built-in 
namespace common to all modules). There is also the problem of 
inadvertently injecting a 'global' name that will clash with the 
internal module-scope names in some modules that are not intended to be 
exported.

The 'from' mechanism deals with that, by creating an alias to the 
/value/ of an exported name without affecting identical names in other 
modules, but it has the problem of not being an alias for the name itself.

-- 
Bartc



More information about the Python-list mailing list