Benjamin-Loison / cpython

The Python programming language
https://www.python.org/
Other
0 stars 0 forks source link

Print begin and end of code section #40

Closed Benjamin-Loison closed 1 month ago

Benjamin-Loison commented 1 month ago
def printState(functionLabel, state):
    print(f'{functionLabel}: {state}')

def printBeginAndEnd(function, functionLabel):
    printState(functionLabel, 'begin')
    function()
    printState(functionLabel, 'end')

myVariable = 42

def function():
    print(f'{myVariable=}')

printBeginAndEnd(function, 'Print `myVariable`')
Print `myVariable`: begin
myVariable=42
Print `myVariable`: end

Preferably would like a scheme like with:

with open('file.txt') as myFile:
    lines = myFile.read().splitlines()
    print(lines)

So without declaring a function, so something like:

myVariable = 42

beginAndEnd 'Print `myVariable`':
    print(f'{myVariable=}')
Print `myVariable`: begin
myVariable=42
Print `myVariable`: end
Benjamin-Loison commented 1 month ago

Related to the Stack Overflow questions 932328 and 3774328.

Benjamin-Loison commented 1 month ago
class PrintBeginAndEnd:
    def __init__(self, sectionLabel):
        self.sectionLabel = sectionLabel

    def __enter__(self):
       self.printState('begin')

    def __exit__(self, _exc_type, _exc_value, _traceback):
       self.printState('end')

    def printState(self, state):
        print(f'{self.sectionLabel}: {state}')

myVariable = 42

with PrintBeginAndEnd('Print `myVariable`'):
    print(f'{myVariable=}')
Print `myVariable`: begin
myVariable=42
Print `myVariable`: end

Modified from https://medium.com/@badu_bizzle/custom-contexts-in-python-24e4525182eb.