[sage-support] Re: How can Sage and Python communicate via global variables?

2016-09-20 Thread Paul Leopardi
Thanks, that all works quite well.


-- 
You received this message because you are subscribed to the Google Groups 
"sage-support" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sage-support+unsubscr...@googlegroups.com.
To post to this group, send email to sage-support@googlegroups.com.
Visit this group at https://groups.google.com/group/sage-support.
For more options, visit https://groups.google.com/d/optout.


[sage-support] Re: How can Sage and Python communicate via global variables?

2016-09-19 Thread Nils Bruin
On Monday, September 19, 2016 at 6:02:22 AM UTC-7, Paul Leopardi wrote:
>
> Hello,
> I am trying to use global variables to control the behaviour of Python 
> functions called from Sage. (Yes, I know there is probably a better way to 
> do it, but I am still interested in what's going on here.)
>
> If in foo.py I have
>
> def bar():
> print blah
>
> def baz():
> global zilch
> zilch = 0
>
> A "global" variable is a "module global" variable. Since you're always 
executing code that is in some module (that's what __main__ is for)

and, in Sage I do:
>
> sage: from foo import bar
> sage: global blah
> sage: blah = 1
> sage: bar()
>

If you spell that foo.blah = 1 it should work (perhaps after executing 
"import foo" in order to have the "foo module namespace" bound to the 
toplevel variable "foo")

 

> sage: from foo import baz
> sage: baz()
> sage: print zilch
>
>  
print foo.zilch

should work


> Is there a way in Sage that I can assign to a global variable that a 
> called Python function will recognize as a global variable?
> Thanks, Paul
>

This is just a python thing: you share global data across modules by making 
sure that this data is bound in a namespace to which both modules have 
access.

There is no really "global" namespace in sage. There's "toplevel", but that 
will generally not be the interactive namespace that a sage interface is 
using, given that ipython, jupyter, and sagenb run "above" your sage code.

You can try and hack your way to the "interactive" namespace. The toplevel 
"var" in sage does that for injection. That's generally fragile, though.

-- 
You received this message because you are subscribed to the Google Groups 
"sage-support" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sage-support+unsubscr...@googlegroups.com.
To post to this group, send email to sage-support@googlegroups.com.
Visit this group at https://groups.google.com/group/sage-support.
For more options, visit https://groups.google.com/d/optout.