0
a = 1
def b():
    for c in range(10):
        if c % 2 == 0:
            a = c
        else:
            a = a
    print(a)
b()

I want to "assgin global.a to b.a", but a = a does not work while it just assign the local a to local a. So how to access the global a and assign it to the a in b?

Do not change the name of a in b.

acgtyrant
  • 1,721
  • 1
  • 16
  • 24
  • 1
    You can't do this. I can't even begin to imagine why you would want to. – Daniel Roseman Jun 27 '16 at 08:14
  • See this code: https://gist.github.com/acgtyrant/ac3ed25b54186ad984c97a1200e49eee @DanielRoseman – acgtyrant Jun 27 '16 at 08:36
  • That gist doesn't show any good reason for wanting to keep the same name as the global function. Why not just call the reference `removal_func` or something like that? – Daniel Roseman Jun 27 '16 at 08:40
  • @DanielRoseman I forget to note that there is a loop statement in `main` actually, so `remove_unvalid_line` in `main` always change; If I do not keep the same name as the global function, I can not drop out a good alternative name... – acgtyrant Jun 27 '16 at 08:54

1 Answers1

3

Use globals(). Though I do not recommend any of this, it can be done. Also, I can't even begin to imagine why you would want to as Daniel commented.

def b():
    for c in range(10):
        if c % 2 == 0:
            a = c
        else:
            a = globals()['a']
        print a
Abdul Fatir
  • 6,159
  • 5
  • 31
  • 58