global declaration from within functions

Joshua Marshall jmarshal at mathworks.com
Wed Aug 15 11:59:49 EDT 2001


Duncan Booth <duncan at nospamrcp.co.uk> wrote:
> Rob Andrews <rob at jam.rr.com> wrote in news:3B7A87D8.6F75B13F at jam.rr.com:

>> I just posted this to the Python Tutor list, so please forgive the
>> cross-posting. I'm just academically curious about this.
>> 
>> *Learning Python* (pp. 99-105) points out that declaring globals from
>> within functions is possible, and shows how. I'm trying to think of
>> *why* one might want to declare or modify a global from within a
>> function.
> You are confused over what the 'global' keyword actually does.

> Most languages, as you say, require you to declare global variables outside 
> functions. Most languages also require you to declare variables. Python 
> does not require you to declare any variables anywhere (even global ones), 
> instead you just assign to them.

> The 'global' keyword doesn't create a new global variable. All it does is 
> to force references to that name, within that local scope, refer to a 
> global variable. If you assign to the variable declared as global then you 
> will update its value. If you reference the variable then you get its value 
> if it exists, or you get an exception if it doesn't exist.

No, Rob is right:

  >>> def f():
  ...    global x
  ...    x = 666
  ... 
  >>> f()
  >>> x
  666

You can use 'global' to define a new variable.



More information about the Python-list mailing list