Using global variables in python in a function - python

def foo():
global a
a = 10
vs
a = 0
def foo():
a = 10
What is the use of declaring global in a function instead of declaring variables right at the top. It should be cleaner this way ?

Q. What is the use of declaring global in a function instead of declaring variables right at the top?
Generally we define few regularly used constants as global variables.
>>> import math
>>> math.pi
3.141592653589793
Mathematical contants/Web Page/Servernames/URLs - which wont change over a period of time.
In general, it is not recommended to RE-DEFINE global variable or define global variables with in a function. But few exception cases are there where we are left with no option but to re-define it. Could be due to a new upgrade in old system where this variable is heavily used across.
So please go with your second approach. Define 'a' outside your
function. This also looks good & easy to read.
>>> a = 10
>>> def foo():
... a = 14 # defining a local variable called a
...
>>> a
10
>>>
>>> foo()
>>> a
10
>>> # a = 14 has no scope outside foo function
>>>
>>> def foo():
... global a # notify function to use global variable here.
... a = 15 # re-defining global ==> nt preferred it
...
>>> a
10
>>> foo()
>>> a # see now it changed here.
15
Hope this helps.

In the first case the value remains same in all the functions.
def set_globvar_to_one():
global globvar
globvar = 1
print globvar
def print_globvar():
print globvar # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar()
The output will be 1 and 1.
But 2nd case
def set_globvar_to_one():
globvar = 1
print globvar
def print_globvar():
print globvar # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar()
Here you get error saying globvar is not defiend, coz there is no local or global variable named globavar

That would make it ambiguous. Look at this,
a = 0
def foo():
a = 10 # *
Look at the line marked *. Are you assigning to the global a or is this a local variable a with a value 10. The interpreter has no way to knowing what you meant. Thus, the need for global.
a = 0
def foo():
a = 10 # local variable a
def bar():
global a # will be modifying global variable a in this function
a = 10 # assign 10 to global variable

In your first example "a" is not available before foo() is called. Once it is defined in the function it available outside of the function.
In the second example it is available before foo() is called butchanges to it inside the function do not affect the global version .
This example should demonstrate the difference between the two examples
#!/usr/bin/python
def foo():
global a
a = 10
print a
try:
print a
except Exception,e:
print e
foo()
print a
print "-"*70
b = 0
def bar():
b = 10
print b
print b
bar()
print b
Output:
global name 'a' is not defined
10
10
----------------------------------------------------------------------
0
10
0

If you declare it as a global, you don't have to return it.
If you don't use global, you have the function to return a.
Without global it be like this:
In [7]: def foo():
...: a = 10
...: return a
...:
In [9]: a = foo()
In [10]: a
Out[10]: 10
With global:
In [11]: a = 0
In [12]: def foo2():
....: global a
....: a = 10
....:
In [13]: a
Out[13]: 0
In [14]: foo2()
In [15]: a
Out[15]: 10
It is you who decide if you want your function to return or to use global.
It can simplify you code, it can be useful for function that calculates some constants that you don't want to call it each time.
But if use it for single procedure, prefer "return" method.

if you are using the same variable inside the loop then there will be a competition between the global and local variable . so if you want to use the value of the global variable in the loop you have to mention the 'global' keyword

Related

Assign global variable to a function's local variable

I want to loop over some global variable i and each time compile a new function that uses the instantaneous value of i. I can then use each of these functions in future, independent of the current value of i.
The problem is I can't find a good way to make the global variable i stay local within the namespace of the function. For example:
i = 0
def f():
return i
i = 1
print(f()) #Prints 1, when I want 0
I found one solution but it seems very clumsy:
i = 0
def g(x):
def h():
return x
return h
f = g(i)
i = 1
print(f()) #Prints 0 as I wanted.
Is there a better way to do this, maybe some kind of decorator?
Python functions are objects, you can set an attribute on them:
i = 0
def f():
return f.i
f.i = i
i = 1
print(f()) # Prints 0 as you wanted
or:
for i in range(5):
f.i = i
print(f())
Note that an argument would do the same.

Pass value to imported script in Python [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 8 months ago.
I'm using functions so that my program won't be a mess but I don't know how to make a local variable into global.
Here are two methods to achieve the same thing:
Using parameters and return (recommended)
def other_function(parameter):
return parameter + 5
def main_function():
x = 10
print(x)
x = other_function(x)
print(x)
When you run main_function, you'll get the following output
>>> 10
>>> 15
Using globals (never do this)
x = 0 # The initial value of x, with global scope
def other_function():
global x
x = x + 5
def main_function():
print(x) # Just printing - no need to declare global yet
global x # So we can change the global x
x = 10
print(x)
other_function()
print(x)
Now you will get:
>>> 0 # Initial global value
>>> 10 # Now we've set it to 10 in `main_function()`
>>> 15 # Now we've added 5 in `other_function()`
Simply declare your variable outside any function:
globalValue = 1
def f(x):
print(globalValue + x)
If you need to assign to the global from within the function, use the global statement:
def f(x):
global globalValue
print(globalValue + x)
globalValue += 1
If you need access to the internal states of a function, you're possibly better off using a class. You can make a class instance behave like a function by making it a callable, which is done by defining __call__:
class StatefulFunction( object ):
def __init__( self ):
self.public_value = 'foo'
def __call__( self ):
return self.public_value
>> f = StatefulFunction()
>> f()
`foo`
>> f.public_value = 'bar'
>> f()
`bar`
Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:
def foo():
global bar
bar = 32
I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.
You could use module scope. Say you have a module called utils:
f_value = 'foo'
def f():
return f_value
f_value is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utils from one module will be accessible to all other modules that have it imported:
>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'
Note that you can import the function by name:
>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'
But not the attribute:
>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'
This is because you're labeling the object referenced by the module attribute as f_value in the local scope, but then rebinding it to the string bar, while the function f is still referring to the module attribute.

Getting the value of a local variable in another function

I'm tinkering around with Python. I have two functions. The first one calls the second, and from the second I am trying to get the value of a local variable within the first, like so:
def b():
local_var = 8
a()
def a():
#get b::local_var here?
I understand that it is possible in python to print out the stack, but I was wondering about accessing the variables and memory within those functions.
Is this even possible?
yes you can, just pass the variable in the function
def b():
local_var = 8
a(local_var) #1
def a(LV): #2
print LV
1
you passed the variable
2
created a new variable LV and assigned the local_var value to LV
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.
So in this case you can use 2 way :
1. define a global variable :
>>> def b():
... global local_var
... local_var=8
... a()
...
>>> def a():
... print local_var
...
>>> a
8
2.pass the variable in a() as its argument :
>>> def b():
... local_var=8
... a(local_var)
...
>>> def a(arg):
... print arg
...
>>> a
8

How to make a local variable (inside a function) global [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 8 months ago.
I'm using functions so that my program won't be a mess but I don't know how to make a local variable into global.
Here are two methods to achieve the same thing:
Using parameters and return (recommended)
def other_function(parameter):
return parameter + 5
def main_function():
x = 10
print(x)
x = other_function(x)
print(x)
When you run main_function, you'll get the following output
>>> 10
>>> 15
Using globals (never do this)
x = 0 # The initial value of x, with global scope
def other_function():
global x
x = x + 5
def main_function():
print(x) # Just printing - no need to declare global yet
global x # So we can change the global x
x = 10
print(x)
other_function()
print(x)
Now you will get:
>>> 0 # Initial global value
>>> 10 # Now we've set it to 10 in `main_function()`
>>> 15 # Now we've added 5 in `other_function()`
Simply declare your variable outside any function:
globalValue = 1
def f(x):
print(globalValue + x)
If you need to assign to the global from within the function, use the global statement:
def f(x):
global globalValue
print(globalValue + x)
globalValue += 1
If you need access to the internal states of a function, you're possibly better off using a class. You can make a class instance behave like a function by making it a callable, which is done by defining __call__:
class StatefulFunction( object ):
def __init__( self ):
self.public_value = 'foo'
def __call__( self ):
return self.public_value
>> f = StatefulFunction()
>> f()
`foo`
>> f.public_value = 'bar'
>> f()
`bar`
Using globals will also make your program a mess - I suggest you try very hard to avoid them. That said, "global" is a keyword in python, so you can designate a particular variable as a global, like so:
def foo():
global bar
bar = 32
I should mention that it is extremely rare for the 'global' keyword to be used, so I seriously suggest rethinking your design.
You could use module scope. Say you have a module called utils:
f_value = 'foo'
def f():
return f_value
f_value is a module attribute that can be modified by any other module that imports it. As modules are singletons, any change to utils from one module will be accessible to all other modules that have it imported:
>> import utils
>> utils.f()
'foo'
>> utils.f_value = 'bar'
>> utils.f()
'bar'
Note that you can import the function by name:
>> import utils
>> from utils import f
>> utils.f_value = 'bar'
>> f()
'bar'
But not the attribute:
>> from utils import f, f_value
>> f_value = 'bar'
>> f()
'foo'
This is because you're labeling the object referenced by the module attribute as f_value in the local scope, but then rebinding it to the string bar, while the function f is still referring to the module attribute.

Convention for declaring variables in Python, when required for scope?

Take this example:
def f():
myvar = None
def g():
print myvar
...
myvar = get_real_value()
g()
Is "myvar = None" a conventional (or at least, reasonable) way of declaring the variable, to make it visible to g()? Is there a better way? (Python 2.6.x, if relevant)
There is no need to declare the variable before the definition for g():
>>> def f():
... def g():
... print myvar
... myvar = 1
... g()
...
>>> f()
1
However, if you can avoid referencing non-local variables in g() that would be preferable, which you would probably do here by having myvar be a parameter to g().
You don't need to pre-initialize the variable; it only has to be initialized before you call g(). Just remove the myvar = None line.
For clarity, I prefer to move local functions as close to their point of invocation as practicable, so that the initialisation of local variables that a function uses comes before the function itself.

Categories