Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
passing an expression
#3
Here is an attempt to do this with a function. In the following code, the function 'expression()' is executed by 'main()' and it uses the variables 'x' and 'y' defined in 'main()'.
import sys
y = 10

class Caller:
    def __init__(self, frame):
        self.frame = frame
    
    def __getattr__(self, attr):
        try:
            return self.frame.f_locals[attr]
        except KeyError:
            return self.frame.f_globals[attr]

def call(func, *args, **kwargs):
    f = sys._getframe(1)
    return func(Caller(f), *args, **kwargs)

    
def spam(u):
    return 5 * u

def expression(caller):
    return caller.x + spam(caller.y)


def main():
    x = 3
    y = 2
    print(call(expression))

if __name__ == '__main__':
    main()
The only thing to do to make it work is to add a first parameter 'caller' in the function's signature and use it to get the variables from the calling namespace. Other parameters can be added to 'expression()' and passed in the 'call()' statement.

The previous code prints 13, but if you comment the line 'y = 2' in 'main()', it prints 53.
Reply


Messages In This Thread
passing an expression - by Skaperen - Feb-16-2021, 10:35 PM
RE: passing an expression - by Larz60+ - Feb-17-2021, 02:29 AM
RE: passing an expression - by Skaperen - Feb-18-2021, 02:39 AM
RE: passing an expression - by Gribouillis - Feb-17-2021, 08:00 AM
RE: passing an expression - by Larz60+ - Feb-18-2021, 11:23 AM
RE: passing an expression - by Skaperen - Feb-21-2021, 12:15 AM
RE: passing an expression - by ndc85430 - Feb-21-2021, 07:36 AM
RE: passing an expression - by Skaperen - Feb-23-2021, 11:41 PM
RE: passing an expression - by ndc85430 - Feb-18-2021, 06:10 PM
RE: passing an expression - by Larz60+ - Feb-21-2021, 09:14 AM
RE: passing an expression - by Skaperen - Feb-23-2021, 11:58 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020