在调用函数之前不久,我们如何恢复定义函数时存在的名称空间(全局名称,本地名称等)?

时间:2019-10-29 12:14:21

标签: python python-3.x namespaces global-variables

我在下面的尝试无效。没有未处理的错误或异常,但是打印到控制台的消息不是所希望的。

import inspect

class Fob:

    def __init__(i, func):
        f = inspect.currentframe().f_back
        i._globals = f.f_globals
        i._builtins = f.f_builtins
        i._locals = f.f_locals
        del f
        i._func = func

    def __call__(i, *args, **kwargs):
        localz = i._locals
        globalz = i._globals

        d = globalz
        d['i'] = i
        d['args'] = args
        d['kwargs'] = kwargs

        r = eval("i._func(*args, **kwargs)", globalz, localz)
        return r
@Fob
def foo():
    """
    GLOBALS: `str`, `print`
    """
    print('apples', 'do I exist?')
    print(str('apples'))


#############################################
#  END OF DEFINING `foo`
#  BEGIN MESSING UP GLOBALS
#############################################

import sys
def print(*args, end="\n", file=sys.stdout, print=print):
    print("SIKE!", type(args[0]), args[0], file=file, end=end)


import string
is_letter = lambda ch, *, str=str:\
    ch in string.ascii_lowercase

str = lambda s, *, str=str, is_letter=is_letter, filter=filter:\
    int(''.join(filter(is_letter, str(s).lower())), 36)


#############################################
#  END MESSING UP GLOBALS. BEGIN CALLING foo()
#############################################

foo()

所需的输出:

apples do I exist?
apples

当前输出:

SIKE! <class 'str'> apples
SIKE! <class 'int'> 647846308

我正在尝试恢复定义函数时存在的名称空间(全局,局部等)。

0 个答案:

没有答案