How does Sage "var" work?

When trying to create a Python function similar to Sage var() or function(), I apparently had a not-so-trivial problem in Python. In fact, a call var('x')in Sage not only returns the symbolic Sage expression, but is equivalent x = SR.var('x'), that is, it assigns the expression object to a variable in the current global namespace (namespace of the calling module).

My question is, how does he do it? If I do something like this:

in B.py:

def func():
    globals()['x'] = something

in A.py

from B import func
func()

I can only affect variables in the global namespace B, not the global namespace of the calling module A.

However, the file var.pyxdistributed with my version of Sage is as follows:

...

def var(*args, **kwds):
    if len(args)==1:
        name = args[0]
    else:
        name = args
    G = globals()  # this is the reason the code must be in Cython.
    if 'ns' in kwds:
        # ...
        # not relevant
    v = SR.var(name, **kwds)
    if isinstance(v, tuple):
        for x in v:
            G[repr(x)] = x
    else:
        G[repr(v)] = v
    return v

...

, Cython . Cython, , , . - Cython, " Python" /CPython?

PS: , , - . .

+4
2

https://groups.google.com/d/topic/sage-devel/J-kDHlnT4/discussion

:

src/setup.py

Cython.Compiler.Options.old_style_globals = True

Cython .

+1

Cython 1.5 changelog, ,

globals() Cython, -Cython-

, Cython.

:

import inspect

def run():
    outer_frame = inspect.stack()[1][0]
    outer_frame_locals = inspect.getargvalues(outer_frame).locals

    outer_frame_locals["new_variable"] = "I am new"

, .

0

Source: https://habr.com/ru/post/1523941/


All Articles