On Dec 27, 2009, at 8:47 AM, Nicolas M. Thiery wrote:
> Hi Robert B and all,
>
> Does anyone know a trick to access the global variables for the "main"
> scope?
>
> In the attached patch (for 4.2; untested on 4.3), I am implementing
> the following in sage.misc.misc_c:
>
> def inject_variable(name, value):
> """
> sage: from sage.misc.misc_c import inject_variable
> sage: inject_variable("a", 314)
> sage: a
> 314
> """
> G = globals()
> G[name] = value
>
> When called from the interpreter, this works just fine. However, the
> purpose is to call this function from library code, and then it
> breaks.
>
> More precisely, if I call this from a Python function, say
> `sage.misc.misc.inject_variable_test` as in the patch, then the
> globals() call returns instead the global variables for the module
> `sage.misc.misc`.
>
> Tips most welcome!
This is because inject_variable is a hack based on the fact that Pyrex/
Cython has a broken implementation of globals()--it should refer to
the module its in, but instead it ends up getting to the last
registered globals in the thread call stack. (I have intentionally not
"fixed" this as I did for locals() because we rely on the broken
behavior, and there are issues for setting a cdef "global").
What we should do is walk up the stack, perhaps looking for __name__
== '__main__'
- Robert
--
To post to this group, send an email to [email protected]
To unsubscribe from this group, send an email to
[email protected]
For more options, visit this group at http://groups.google.com/group/sage-devel
URL: http://www.sagemath.org