简体   繁体   中英

Python function declare a dynamic global variable

I saw the code below and I'm speechless. Here it is:

>>> import sympy
>>> sympy.var('x')
x
>>> x
x
>>> type(x)
<class 'sympy.core.symbol.Symbol'>
>>>

Notice that that the variable x has never been assigned. What's going on?

In my opinion the function sympy.var accepts a string as an input parameter and declares a global variable of type sympy.core.symbol.Symbol whose name is equivalent to the parameter. So every time the function is called, a new variable will be available whose name is the last parameter passed to the function.

From the ( DOCS )

sympy.core.symbol.var(names, **args)

Create symbols and inject them into the global namespace.

To add some details to @Stephen Rauch's answer, have a look at core source code:

from inspect import currentframe
frame = currentframe().f_back

try:
    syms = symbols(names, **args)

    if syms is not None:
        if isinstance(syms, Basic):
            frame.f_globals[syms.name] = syms
        elif isinstance(syms, FunctionClass):
            frame.f_globals[syms.__name__] = syms
        else:
            traverse(syms, frame)
finally:
    del frame  # break cyclic dependencies as stated in inspect docs

As you can see, using inspect.currentframe().f_back.f_globals , you can get current globals .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM