'Python mutating __builtins__ has different behaviour in REPL

I'm attempting to make it so that, instead of raising a NameError when an undefined variable is referenced, it instead calls a function that I've defined to get the value.

Background

I'm a relatively advanced Python programmer, and no beginner. This question is not for practical application but for personal learning.

What I've tried so far

I tried to use __builtins__.__missing__ as my function, but it only worked in shell. This works in the Python interactive console on 3.9.1:

>>> __builtins__=type('', (dict,), {'__missing__': lambda *args: args[1]})(__builtins__.__dict__)
>>> print(variable)
variable

However, when I run it as a program, it throws NameError: name 'variable' is not defined

__builtins__=type('', (dict,), {'__missing__': lambda *args: args[1]})(__builtins__.__dict__)
print(variable)

Question

What's going on here, and how can I handle this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source