Python : define a constant used by several functions [duplicate] - python

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.

Related

How to change a variable and keep the change from a function inside a function

#a test to see how to call and modify a variable by a function inside a function!
test_variable = "Hello __1__ !!, I'm good, How about you!!"
#function 1 to save to variable
def test_function_1():
global test_variable
hello = test_variable
return hello
#function 2 to use the variable through function 1
def test_function_2(test):
global test_variable
word = raw_input("Hi, Enter your word\n")
print
test = test.replace("__1__", word)
return test
#See how the function work!
print test_function_2(test_function_1())
#See if the variable changed by the function or not!
print test_variable
I can't keep the change to the variable. I try global in every function and it didn't work.
Remember in python, strings are immutable. So you can't change them. (I am guessing by 'I can't keep the change to a variable', you were expecting the global test_variable to change as well.
You are essentially assigning names. This talk is a good place to start to understand some core python concepts:
https://www.youtube.com/watch?v=_AEJHKGk9ns

values arguments in pdg

I have created a simple function on python and make some tests with the debugger to see how it works.
I wanted to print the value of a variable (raiz):
(dbg) p raiz
But it says that it's not defined. Why is this? Here is my code:
import math
def funcion(sen):
raiz = math.sqrt(sen)
return "the sqrt of " + repr(sen) + 'is ' + repr(raiz)
print (funcion(38))
import pudb;
pudb.set_trace()
Your variable is declared inside the function, not outside, so the code can't see it.
If you need to set value for outside variable, mark it with global keyword (which is a bad practice):
import math
raiz = None
def funcion(sen):
nonlocal raiz
raiz = math.sqrt(sen)
return "the sqrt of " + repr(sen) + 'is ' + repr(raiz)
funcion(38)
print (raiz)
Also you can use nonlocal keyword, but for this case it would fail with:
SyntaxError: no binding for nonlocal 'raiz' found
You can find a tutorial about local, nonlocal and global keywords here.
This is to do with Scope.
The place that variables are defined is important, and defining them in certain places will cause them to disappear elsewhere. Here is an example:
# PLEASE NOTE: This code will fail.
a = "Hello"
def my_func():
b = "Hello" # Declare a variable 'b', but only in this scope, in other words this function.
my_func()
print(a) # Works, since a is in the same scope.
print(b) # Fails, since b was defined inside a different scope, and discarded later.
Since, in your example, raiz was declared inside the function funcion, Python discarded it after funcion was called. If you put the line:
raiz = 0
before your function definition, the function would simply update the variable, so there would be no issue, since the scope would be the same as where the print statement occurs.
tl;dr: The variable raiz was declared only in funcion, so it was discarded afterwards.

How to set a global variable

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

Order of execution in Python methods [duplicate]

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

Declaring global variables

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.

Categories

Resources