Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to access the updated global variable's value

Suppose I have two Python files:

  1. abc.py:
from .config import *
update_a()
print_a() # prints 5
print(a)  # prints 2 rather than 5 even after calling update_a() and using global in update_a()
  1. config.py:
a = 2

def update_a():
    global a
    a = 5

def print_a():
    global a
    print(a) # prints 5

The global variable in config.py does not seem to have the updated value when accessed from abc.py.

like image 806
Tamil Selvan Avatar asked Jan 27 '21 06:01

Tamil Selvan


People also ask

Can you update a global variable?

If it's been created globally, then you'll be updating the global variable. You can override this behaviour by declaring it locally using var , but if you don't use var , then a variable name used in a function will be global if that variable has been declared globally.

How do you reset global variables?

On the Global Variable List panel, you can delete a variable by positioning your cursor on the line you want to delete and pressing the Delete key.

Can you change global variables in Java?

You don't. There are no global variables in Java.

Can you declare global variables in C?

The C language allows the redeclaration of the global variable. It means that this variable can get declared again when the first declaration doesn't lead to the initialization of the variable. It is possible because the second program works pretty well in the C language even if the first one fails during compilation.


1 Answers

When you do an import say from .config import *, the variable a is imported as a local scope. Any modification to a will happen within the scope in abc.py NOT in config.py whereas the call to update_a() and print_a() is modifying the variable a within config.py

like image 92
Joe Akanesuvan Avatar answered Oct 18 '22 03:10

Joe Akanesuvan