我如何知道在 python 中调用了我的函数的哪个代码块

How do I know which block of code my function is getting called in, in python

我有以下class

class Time:
    def __init__(self) -> None:
        self.time  = 0;
    def __enter__(self):
        self.start = time()
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end  = time()
        self.time = self.end - self.start
        print(f'The execution of the block took {self.time}s')

我这样称呼它

with Time():
    # block 1
    for i in range(100000):
        for ii in range(100):
            pass
    with Time():
        # block 2
        for i in range(1000):
            prime(i)
        with Time():
            # block 3
            ''

这是我得到的输出:

The execution of the block took 1.6689300537109375e-06s
The execution of the block took 0.0006444454193115234s
The execution of the block took 0.4997687339782715s

在顺序块 3、2、1 中。

但是如果我有一个更大的程序,我将如何检查哪个块正在调用我的函数呢?

我试过这样做:

print(f'The execution of the block {locals()} took {self.time}s')

但这只是给我 class 的本地人。

您可以使用带有标签的字符串参数。

代码:

class Time:
    def __init__(self, label="") -> None:
        self.time = 0
        self.label = label

    def __enter__(self):
        self.start = time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time()
        self.time = self.end - self.start
        if not self.label:
            print(f'The execution of the block took {self.time}s')
        else:
            print(f'The execution of the block {self.label} took {self.time}s')

如果您希望块名称为 1 到块数,您可以使用 class 变量,这是 Python 的一大特点。

代码:

class Time:
    index = 0

    def __init__(self) -> None:
        self.time = 0
        self.index = Time.index
        Time.index += 1

    def __enter__(self):
        self.start = time()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end = time()
        self.time = self.end - self.start
        print(f'The execution of the block {self.index} took {self.time}s')