This question already has answers here:
Using global variables in a function
(25 answers)
Closed 4 years ago.
How can I define a global variable.
For example I have Foo1 class and Foo2 class and I want to use FooVariable in this classes as a global variable.
If you wanted a global variable named foo, you would just have to put global foo at the top of any function in which it is used. For example,
def do_something():
global foo
foo = foo + 1
print foo
Note that Python "global" variables are only global to the module they appear in, not global to the entire program (as in some languages).
Related
This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 4 months ago.
test=4
def sum1(var):
print("in function, test",test)
var+=1
test=7
print("in function, var",var)
print("in function, test",test)
sum1(5)
print(test)
I'm trying to understand global and local variable, so I try it this way: a global and a local variable that has same names (I know we normally don't do that).
In this program it has an "UnboundLocalError: local variable 'test' referenced before assignment"
I am wondering why the first print() that prints the test cannot be printed out? Why wouldn't it call the global "test"?
Because your local test shadows the name of the global test, it's unclear to which one you're referring. If you comment out the line test = 7 in your function, you won't get the error, as python assumes you're referring to the global test.
If you insist on using var names in your local scope that shadow global vars (and you've just discovered why that's a very bad idea), you can be explicit about it:
def sum1(var):
global test
print("in function, test", test)
...
Now, however, when you get to test = 7, you're modifying the global test var. That's probably not what you wanted.
This question already has answers here:
Global dictionaries don't need keyword global to modify them? [duplicate]
(2 answers)
Closed 2 years ago.
This executes without error:
def myfunction():
global a_dict
a_dict['s'] = 'whatevs'
b_dict['s'] = 'lalala'
a_dict = b_dict
a_dict = {'s':[], 'm':[]}
b_dict = {'s':[], 'm':[]}
myfunction()
Why does this not throw an error without also adding global b_dict to the function - as I'm writing to both dictionaries?
It sure does if I comment out the global a_dict ("'a_dict' referenced before assignment") - as I would expect.
You only need global foo when you want to assign to the global name foo. You are not assigning to b_dict; you are assigning to one of its keys, equivalent to b_dict.__setitem__('s', 'lalala'). Both uses of b_dict treat it as a free variable, since there is no local variable named b_dict defined.
The value of a free variable is taken from the closest enclosing scope (in this case, the global scope) where it is defined.
The fact of declaring a variable as global in a function allows you to use a variable outside that function. If there is no variable b declared inside it, Python is going to assume it is a global variable declared before the function call.
This question already has answers here:
Visibility of global variables in imported modules
(9 answers)
Closed 3 years ago.
main1.py
import mya
a=10
mya.increment_a()
a=a-5
print(a)
module mya.py
def increment_a():
global a
a=a+1
print(a)
name 'a' is not defined.
I don't understand why. I declare variable a as global in module, so from this point a=0 as it is in mail1.py
upd: I need work globaly. Starting value for variable "a" set in main.py, function in module mya.py will edit "a", and return new value to main.py for further use.
--- closed topic---
Now I use "arguments" and "return" and in work:
mya.py
def increment_a(a):
a=a+1
print(a)
return a
main1.py
import mya
a=0
print(a)
a=mya.increment_a(a)
a=a+10
print(a)
From Visibility of global variables in imported modules:
Globals in Python are global to a module, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it static.)
One approach to deal with it is:
import mya
mya.a=3
mya.increment_a()
This question already has answers here:
Using global variables in a function
(25 answers)
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 5 years ago.
Why is this code giving 'UnboundLocalError: local variable 'num1' referenced before assignment' error?
num1=50
def func():
print(num1)
num1=100
func()
Another gotcha! of python. This is because of hoisting and variable shadowing. If you have a local and global variable with the same name in a particular scope, the local variable will shadow the global one. Furthermore, declarations are hoisted to the top of their scope.
So your original code will look something like this:
num1=50
def func():
num1 = ... # no value assigned
print(num1)
num1=100
func()
Now, if you try to print num1 without having assigned any value to it, it throws UnboundLocalError since you have not bound any value to the variable at the time you are trying to dereference it.
To fix this, you need to add the global keyword to signify that num1 is a global variable and not local.
num1=50
def func():
global num1
print(num1)
num1=100
func()
This question already has answers here:
Short description of the scoping rules?
(9 answers)
Using global variables in a function
(25 answers)
Closed 5 years ago.
I have a question regarding globals() in python
My sample code
b=9
def a1():
'kkk'
a1()
print globals()
I got output b as global
Since b is global, I am expecting I can modify it anywhere
So I modified my code to
b=9
def a1():
'kkk'
b=100
a1()
print globals()
still my globals() says b as 100. Why b inside the function is taken as local value while my globals() says its global?
Note: If I add keyword global b inside the function, it get convert to global.
My question is why b was not getting modified inside the function while globals() declare b as global ?
Refer Python docs for more information. Copying the text in case URL doesn't work
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.
inside a function, unless you use the keyword global, it is not global variable that is modified. instead,a local variable is created and is destroyed as soon as it is out of scope
As your code b is a local variable in a1(), to use global variable, you should first say that to python and then use it, as follows:
b=9
def a1():
'kkk'
global b
b=100
a1()
print globals()