[Tutor] calling global in funtions.

Alan Gauld alan.gauld at btinternet.com
Wed Feb 26 14:37:40 CET 2014


On 26/02/14 07:12, Santosh Kumar wrote:
> All,
>
> Requirement : i want to call a variable assigned outside a function
> scope anytime within the function.

call in Python means something very specific, namey that you put parens 
after the name and that hopefully results in some code being executed.
You call dir by writing dir().

I assume you just mean you want to access a global variable (which is 
usually a bad idea and its better to pass it in/out of your function)


> I read "global" is a way.

Yes, you specify that the variable is global using the global keyword

global a


> a) Case I looks fine.

Yes, that's the correct usage.

> b) Case II is bombing out.
> CASE II:
>
> In [21]: a = 10
>
> In [22]: def fun_local():
>     ....:     a = 5

This creates a new local variable 'a' in your function.

>     ....:     print "the value of a is %d" %(a)
>     ....:     global a
 > <input>:4: SyntaxWarning: name 'a' is assigned to before global 
declaration

This tries to tell the function that 'a' is global but it already has a 
local 'a' so if this worked you would lose that local variable. So 
Python issues a warning to tell you so. You must specify global before 
Python tries to create a local variable of the same name.

And if you are just reading the value then you don't need to specify 
global at all, you can just read it and Python will find it. But it's 
still better practice to pass the value in as an argument than to use 
globals.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list