On Sep 29, 2010, at 07:42 , Walker wrote:

> Hi everybody.
> I'm experiencing problems with global variables in Sage. In
> particular, I noticed that if I create a global variable, that one is
> known everywhere and it's possible to call it everywhere. If I make an
> assignment to a variable with the same name of the global one, but
> inside a function in another file, it automatically creates a local
> variable and makes the global one unknown inside the function itself,
> but only outside it. My question is: is there a way to make Sage not
> creating a global variable but assigning directly the global one?

Remember that Sage uses Python as its underlying language, so (most of) the 
rules of Python apply here.  For most programming questions, the Python 
documentation will give you a lot of help.

Also, in general, a small snippet of code, showing the problem you are having, 
along with your request for help can simplify our job in helping you.

In this case, you problem seems pretty clear, and is answered by the Python doc:

In the scope of a procedure, all variables are local, not global, unless 
explicitly specified.  The way to do this is with the 'global' statement, which 
should list the global variables that you want to access within the scope of 
your procedure.

Note that if you name a variable in a global statement, and one of that name is 
not in global scope, it will be created if you assign to it.

Thus the following:

sage: def xx(n):
   ...:    global fred, ralph
   ...:    fred = n
   ...:    
sage: xx(3)
sage: fred
 3

However, if you don't assign to a non-existent global variable, and just refer 
to it, you will get a thrown exception:

sage: def xx(n):
   ...:    global fred, ralph
   ...:    print ralph
   ...:    
sage: xx(3)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)

/Volumes/Zeppo/SandBox/Justin/sb/Sage/<ipython console> in <module>()

/Volumes/Zeppo/SandBox/Justin/sb/Sage/<string> in xx(n)

NameError: global name 'ralph' is not defined

HTH

Justin

--
Justin C. Walker
Curmudgeon-at-large
Director
Institute for the Absorption of Federal Funds
----
186,000 Miles per Second
Not just a good idea:
  it's the law!
----

-- 
To post to this group, send email to sage-support@googlegroups.com
To unsubscribe from this group, send email to 
sage-support+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sage-support
URL: http://www.sagemath.org

Reply via email to