Is there a way to get the source code inside the context manager as a string?

The source code of the function can be obtained using the function inspect.getsourcelines(func). Is there a way to do this for the context manager?

with test():
    print('123')

# How to get "print('123')" as line here?
+4
source share
1 answer

What do you think of this decision?

import traceback


class ContextManagerContent(object):

    def __enter__(self):
        return

    def __exit__(self, _type, value, _traceback):
        stack = traceback.extract_stack()
        f, last_line = self._get_origin_info(stack)

        with open(f) as fin:
            lines = list(fin)

        search = 'with {cls_name}'.format(cls_name=self.__class__.__name__)
        for i, x in enumerate(lines[:last_line + 1][::-1]):
            if search in x:
                first_line = len(lines) - i
                break

        selected_lines = lines[first_line:last_line + 1]
        print ''.join(selected_lines)

    def _get_origin_info(self, stack):
        origin = None
        for i, x in enumerate(stack[::-1]):
            if x[2] == '__exit__':
                origin = stack[::-1][i + 1]
                break

        return origin[0], origin[1] - 1


with ContextManagerContent():
    print '123'
    print '456'
    print '789'

If you save it in a file .pyand run it, you will see that you are printing the numbers 123, 456 and 789, after which you can see the context manager block.

Note that I did not handle exceptions or formatting the output, and some parts could be improved, but I think this is a good starting point.

+2
source

All Articles