I tried to set a global variable in a funktion.
global the variable is set to Kategorie = ''
In one of my function I would like to set it to a other value:
elif methode=='show_select_dialog':
writeLog('Methode: show select dialog', level=xbmc.LOGDEBUG)
dialog = xbmcgui.Dialog()
cats = [__LS__(30120), __LS__(30121), __LS__(30122), __LS__(30123), __LS__(30116)]
ret = dialog.select(__LS__(30011), cats)
if ret == 6:
refreshWidget()
elif 0 <= ret <= 5:
writeLog('%s selected' % (cats[ret]), level=xbmc.LOGDEBUG)
global Kategorie
Kategorie = (cats[ret])
refreshWidget()
If I log the variable Kategorie in function refreshWidget the value is correct (cats[ret]), but after that if the function refreshedWidget is called again the value is gone...
elif methode == 'get_item_serienplaner':
sp_items = refreshWidget()
Once I have changed the variable to cats[ret] I would need it as cats[ret]
You have to declare your var outside your functions and everytime you want to use it inside a function you need to specify the global varName. As i see your global var name at declaration is Kategory and after you use Kategorie.
Python wants to make sure that you really know that you are using global variables by explicitly requiring the global keyword.
To use a global variable within a function you have to explicitly delcare you are using it.
Here a small example:
myGlobalVar= 0
def set_globvar():
global myGlobalVar # Needed to modify global copy of globvar
myGlobalVar = 5
def print_globvar():
print myGlobalVar # No need for global declaration to read value of myGlobalVar
set_globvar()
print_globvar() # Prints 5
in your case I see that you declare that you want to access global Kategorie but you do not declare access to global Kategory. I do not know if this is a simple typo or if they are 2 different variable. In any case you need to write global yourGlobalVariable
Are there really any globals in python? Yes there is a global keyword that allows you to access varibles in file scope. Another way of accessing the variable is to use the import statement. Lets say you have a file named file.py. In order to write to the variable you could. You could access another files variables just as easy.
import file
anyVariable = 42
# ...
def aFunc():
file.anyVarible = file.anyVarible + 1
Related
This question already has answers here:
Why isn't the 'global' keyword needed to access a global variable?
(11 answers)
Closed 2 years ago.
In Python, I was wondering something about defining a variable in a module which can be used by all functions in that module.
I know that if I define a variable outside function, I can access that variable in a function by introducing global
e.g : inside a module name gas.py
R = 8.314 # univsersal gas constant
def pressure(T, V, n):
global R
P = n*R*T/V
return P
def temperature(P,V,n):
global R
T = P*V/(R*n)
return T
But as you can see, I have to write global R inside each function.
Is there a way that I can access R without writing global R inside each function ?
For example :
R = 8.314 # univsersal gas constant
def pressure(T, V, n):
P = n*R*T/V
return P
def temperature(P,V,n):
T = P*V/(R*n)
return T
Thank you
In python, you can read the value of a global variable without declaring it global.
You only need the global declaration when you want to change the value of a global variable. So in your case, you can just delete the all global declarations.
No, in Python a global variables works in a different way compared to other programming languages.
If you want to access a variable contained outside a function, you can just call it like a regular variable, for example:
word = "hello"
def function():
print(word)
function()
Output: hello
If you want to edit a variable locally, but not globally, you have to reassign the variable inside the function, for example:
word = "hello"
def function():
word = "world"
print(word)
print(word)
Output: hello, because we reassigned the variable only inside the function, so the global value of the variable word is still hello
But, if we want to edit a global variable (such as in case 1) in a non-global scope (local scope) and we want to manipulate the value of that variable inside a function, we have to use the global declaration, for example:
word = "hello"
def function():
global word
word = "world"
function()
print(word)
Now the Output will be world.
Class 'Test' contains function 'test_variables'.
Functions 'update_d' and 'update_a' are declared within 'test_variables()'.
Variable 'index' is initialized to 0 in 'test_variables'
List A [1,2] is initialized in 'test_variables'
'update_d' and 'update_a' updates 'index' and prints it.
I can access elements of list A without using the global attribute,
but to access 'index' I have declared'global index' within 'update_d' and 'update_a'.
Why can I not access the variable index without global but can access a list?
index=0
class Test():
def test_variables():
def update_d():
global index
index=index+1+A[0]
print(index)
def update_a():
global index
index=index+1+A[1]
print(index)
index=0
A=[1,2]
update_d()
update_a()
test_variables()
In Python, the global keyword is only needed when you are writing to a variable. Inside test_variable() you have defined a NEW variable named index, though it seems your intent was to write to the variable defined outside that scope.
When you read from a variable name, Python starts in the innermost scope and if the name isn't found, continues looking in the containing scopes.
When you write to a variable name, Python only looks locally and creates a new variable if one of that name isn't found. The global keyword tells Python that the local scope should reference that name globally on assignment.
For this reason, global variables work best as constants, and variables you need to change should probably be passed in to a function as a parameter and the new value returned.
The list A (in addition to update_a and update_b) is defined within Test, while index is not.
It's not correct way of using classes.
Code:
class Test:
A = (1, 2)
def __init__(self, index):
self.index = index
def update_d(self):
self.index += 1 + self.A[0]
print(self.index)
def update_a(self):
self.index += 1 + self.A[1]
print(self.index)
def test_variables(self):
self.update_d()
self.update_a()
idx = 0
tst = Test(idx)
tst.test_variables()
Provided code does same as yours but with correct usage of classes.
I came across this problem of not being able reference golbal variables from inside of a function. It always throws an error saying "local variable 'variable_name ' referenced before assignment".
I wrote a simple code which will throw the same error in trying to return a array of product of two numbers.
table=[]
counter = 0
def multiplier(num):
if counter >9:
print (table)
else:
table.append(num*counter)
counter +=1
multiplier(num)
multiplier (5)
What am I doing wrong here? My original code requires the function to be called again and again for that I want to use a counter to keep track of how many times it is being called. This means I cannot initialize the counter inside of the function because once the function is called and because the counter is initialized inside the function, it will be reset.
Use global keyword at the first line in your function block.
Like:
def multiplier(num):
global counter
...
You have to declare
global counter
in your function to access the global variable instead of creating a local variable of the same name. The nicer solution would be to define a class, though.
Make counter a parameter of the function with a default value of zero. When you recurse, add one to the count.
table=[]
def multiplier(num, counter = 0):
if counter >9:
print (table)
else:
table.append(num*counter)
multiplier(num, counter+1)
multiplier(5)
Here is your function refactored to return a value instead of printing it.
table=[]
def multiplier(num, counter = 0):
if counter >9:
return table
else:
table.append(num*counter)
return multiplier(num, counter+1)
print(multiplier(5))
You can use global keyword to use the global variable. Following points to keep in mind:
Use global keyword only when you are changing the global variable value.
You can use global variable if only reading just by using the variable name (global variable definition not required here).
Example:
var = 10
def change_var():
global var
var = 2
return var
def read_var():
print "Variable is:",var
Hope this helps.
This question already has answers here:
Assigning to variable from parent function: "Local variable referenced before assignment" [duplicate]
(5 answers)
Closed 9 years ago.
I've tried looking at a few different examples, but I'm not really sure why this isn't working. Say I've some code like this:
def loadVariable():
global count
count = 0
def loadDictionary():
location = 'some location'
global myDict
myDict = pickle.load(open(location, 'rb'))
def main():
loadVariable()
loadDictionary()
for item in myDict:
if item.startswith("rt"):
count += 1
item = item[3:]
if __name__ == '__main__':
main()
To my eyes, the if statement is executed which starts the main() method. Then, the variable which is global is loaded, the dictionary is loaded and the for loop is executed.
However, when I run the code I am told that the local variable count is referenced before its assignment. Why is that happening?
Edit (Explaining some of the things I've written in comments):
This doesn't work (although I think that's because global is used wrong here):
global count
def loadVariables()
count = 0
def main():
loadVariables()
rest of code etc
This doesn't work either:
def loadVariables()
count = 0
def main():
global count
loadVariables()
rest of code etc
The only way thus far I've gotten it to work is using the link provided above, which is to treat the count as a list, like so:
def loadVariables():
global count
count = [0]
def main():
loadVariables():
rest of code etc
count[0] += 1
global means that within the function containing the global declaration, the name in the global declaration refers to a global variable. It does not mean "this thing is a global variable; treat it as global everywhere." In main, the names count and myDict refer to local variables, because main does not declare that it wants to use the globals.
The issue is that you're not declaring count as a global variable in the main function, so when the compiler sees that you're (eventually) assigning to it, it assumes that it's a local variable. Since it's value is read before it's assigned, you get an exception.
So, the most basic fix is just to add global count at the top of main(), but I think avoiding globals would be a better option. Why not have loadVariable and loadDictionary return their results, rather than assigning them to globals? If in main() you did count = loadVariable(), count would be a local variable, and you'd have no problems later trying to reassign it.
Here's a simple example of how global works
global_var = 0
def updater():
global global_var
global_var += 1
def stuff(x):
updater()
return global_var + x
if __name__ == '__main__':
stuff(2) # returns 3
I have 2 question regarding global variables:
Why can't I declare a list as a global variable as so: global list_ex = []?
I have already defined a global variable that I am trying to use in a function, but can't:
global column
def fx_foo(cols):
common = set(cols).intersection(set(column)) #Error Here!!
When I try to access column inside the function, I get an error:
NameError: global name 'column' is not defined
You are not using global correctly. You don't need to use it at all.
You need to actually set a global column variable, there is none right now. global does not make the variable available. Just create a global column first:
column = []
then refer to it in your function. That is what the NameError exception is trying to tell you; Python cannot find the global column variable, you didn't assign anything to the name so it doesn't exist.
You only need to use global if you want to assign to a global column in your function:
def somefunction():
global column
column = [1, 2, 3]
Here the global keyword is needed to distinguish column from a local variable in the function.
Compare:
>>> foo = 1
>>> def set_foo():
... foo = 2
...
>>> set_foo()
>>> foo
1
to
>>> foo = 1
>>> def set_foo():
... global foo
... foo = 2
...
>>> set_foo()
>>> foo
2
The first form only set a local variable, the second form set the global variable instead.
The keyword global means you are explicitly using a variable declared outside the scope of a function.
Your variable must be declared normally:
column = []
and declared global in the function that uses it
def fx_foo(cols):
global column
common = set(cols).intersection(set(column))
It is used to allow python to distinguish between new local variables and reused global variables.
this will work :
column =[]
def fx_foo(cols):
global column
common = set(cols).intersection(set(column))
but this will work even without global as column will be considered as nonlocal here
column =[]
def fx_foo(cols):
common = set(cols).intersection(set(column))
I think It is more interesting to assign data to column if You want to display global feature (as You can use column from nonlocals without global declaration if you don't assign anything to it)
column =[]
def fx_foo(cols):
global column
column = set(cols).intersection(set(column))
or
def fx_foo(cols):
column =[]
global column
column = set(cols).intersection(set(column))
Global variables need to be declared global inside of the function not on the outside. A variable declared outside a function is by default global.
Functions don't need to declare a variable as global if they only need to access it. The global declaration is just if you need to modify the global variable.
Therefore, in your case, I suggest that you look into what column actually is when you're passing it to the function, because I think the problem may have something to do with that.