how to acces the block inside of a context manager as sourcecode

Daniel invalid at invalid.invalid
Thu Nov 20 11:43:48 EST 2008


Hi Aaron,

the dataStore combines both the printing and analysis (it will create a
report).
Unfortunately the end of the block already needs to be known in
__enter__, as the report starts to print during the measurement.
I decided to do it the following way:

__enter__ gets the start line number using the idea you proposed.
then the program reads the number of lines that are indented with
respect to the with block. This could cause problems for strange
indenting, but this should not happen in my application. Unfortunately I
could not use the ast module, because the comments are an important part
of the report.

Thank you for your ideas

Daniel




class CM( object ):
    def __enter__(self):
        self.startline= inspect.stack( )[ 1 ][ 0 ].f_lineno
        print 'startline',self.startline
        filename = inspect.stack( )[-1][1]

        def getIndentation(line):
            # TODO: handle comments and docstrings correctly
            return len(line) - len(line.lstrip())

        with open(filename,'r') as f:
            lines=f.readlines()[self.startline-1:]
            indent0=getIndentation(lines[0])
            indent =[getIndentation(i)-indent0 for i in lines[1:]]
            nlines = [n for l,n in zip(indent,xrange(1,1000000)) if l >
0][0]
            self.callingCode = lines[:self.startline+nlines]

        print self.callingCode


    def __exit__(self, exc_type, exc_value, traceback):
       pass

if __name__ == '__main__':
    with CM():
        print 'in first'
        a= 0
        b= 1
        c= 2
        print 'end of first'

    with CM():
        d= 3
        e= 4



More information about the Python-list mailing list