Есть ли способ вручную установить глобальное пространство имен для конкретной функции? - PullRequest
0 голосов
/ 28 октября 2019

Мы ищем реализацию для set_globals в псевдокоде ниже:

def foo():
    """
    GLOBALS: `str`, `print`
    """
    print('apples', 'do I exist?')
    print(str('apples'))

foo_dot_globals = {'print':print, 'str':str, 'globby':1}
# set_globals(foo, foo_dot_globals)

#############################################
#  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)

str = lambda s, *, str=str:\
    int(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

МЫСЛИ:

Может быть, мы могли бы использовать какую-то комбинацию inspect.currentframe().f_back, gc.get_referents, ctypes или другие инструменты из одной из более мощных, но страшных стандартных библиотек?

1 Ответ

1 голос
/ 28 октября 2019

Вы можете захватить глобальное пространство имен функционального объекта следующим образом:

>>> exec(foo.__code__, foo_dot_globals)
apples do I exist?
apples
...