[Tutor] calling global in funtions.
Steven D'Aprano
steve at pearwood.info
Wed Feb 26 14:45:42 CET 2014
On Wed, Feb 26, 2014 at 12:42:00PM +0530, Santosh Kumar wrote:
> All,
>
> Requirement : i want to call a variable assigned outside a function scope
> anytime within the function. I read "global" is a way.
You can *read* the value of a global from inside a function without
needing to declare it at any time. In fact, this is how you can call
other functions -- they are just globals that you read.
So this will work:
a = 10
def func():
print("a equals %s" % a)
func()
=> prints "a equals 10"
But if you want to re-assign a global, you need to declare it global
first. By default, if you say "x = ..." inside a function, Python will
treat that variable x as a local variable. So here's an example:
a = 10
def func():
global a
print("Before, a equals %s" % a)
a = 23
print("After, a equals %s" % a)
func()
=> prints "Before, a equals 10" and "After, a equals 23")
> a) Case I looks fine.
> b) Case II is bombing out.
Actually no it isn't. You're just getting a warning, not an error. See
below.
> Is this how it works or please correct me if i am wrong.
>
> case I:
>
> In [17]: a = 10
>
> In [19]: def fun_local():
> ....: global a
> ....: print "the value of a is %d" %(a)
> ....: a = 5
> ....: print "the value of a is %d" %(a)
> ....:
>
> In [20]: fun_local()
> the value of a is 10
> the value of a is 5
This is completely fine.
> CASE II:
>
> In [21]: a = 10
>
> In [22]: def fun_local():
> ....: a = 5
> ....: print "the value of a is %d" %(a)
> ....: global a
> <input>:4: SyntaxWarning: name 'a' is assigned to before global declaration
> <input>:4: SyntaxWarning: name 'a' is assigned to before global declaration
> <input>:4: SyntaxWarning: name 'a' is assigned to before global declaration
This is just a warning. It is STRONGLY RECOMMENDED that you put the
global declaration at the top of the function, but it is not compulsary.
If you put it somewhere else, you will get a warning, but the function
will still work.
For now. Some day Python may change that behaviour, so it is safest if
you move the global to the top of the function.
--
Steven
More information about the Tutor
mailing list