On Wed, Sep 29, 2010 at 8:18 AM, Simon King <simon.k...@nuigalway.ie> wrote:
> Hi Walker!
>
> On 29 Sep., 16:42, Walker <ebwal...@gmail.com> wrote:
>> ... My question is: is there a way to make Sage not
>> creating a global variable but assigning directly the global one?
>
> This is actually a Python question.

Yes.

> It would of course be very
> dangerous if variables defined outside a function would influence what
> happens inside a function.

No, that's the expected and useful behavior. Otherwise you couldn't
even call other functions from your function (as they are just
"variables").

> So, unless you explicitly declare *inside
> the function* that a variable is global, it won't be visible inside
> the function.
>
> So, you could do:
> sage: def f():
> ....:     global x
> ....:     print x
> ....:
> sage: x=3
> sage: f()
> 3
> sage: x=5
> sage: f()
> 5

Your f will have the same behavior even if x is not declared global.
It works just as it does in Python. Global variables are by default
readable but not writeable from the local scope, so if you do an
assignment and don't declare a variable to be global, then a local
shadow will be created. (Function arguments are considered assignments
as well.) In other words, variable declaration in Python is done by
assignment (as opposed to other languages where it is explicit). An
example is worth a thousand words:


sage: x = "this is x"
sage: y = "this is y"
sage: z = "this is z"
sage: def f():
....:     print x
....:     y = "new value"
....:     print y
....:     global z
....:     z = "new value"
....:     print z
....:

sage: f()
this is x
new value
new value

sage: x, y, z
('this is x', 'this is y', 'new value')

- Robert

-- 
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