如何检查 python 函数是否更改(在实时代码中)? [英] How do I check if a python function changed (in live code)?

查看:79
本文介绍了如何检查 python 函数是否更改(在实时代码中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个函数的引用,我可以检查它的代码对象 f.__code__,获取一个签名,然后对该签名执行稍后检查以查看代码是否更改.这很好.但是如果函数的依赖项之一发生了变化呢?例如

If I have a reference to a function I can check it's code object f.__code__, get a signature, then perform later checks against this signature to see if the code changed. This is good. But what if one of the funciton's dependencies changed? E.g.

def foo(a, b):
    return bar(a, b)

假设 foo 保持不变,但 bar 改变了.有没有办法可以通过 foo.__code__ 对象检查 foo 的依赖项实时"(与解析文本和使用 AST 相比)?

Let's say foo remained the same, but bar changed. Is there a way I can check foo's dependencies 'live' via the foo.__code__ object (vs. parsing the text and using AST)?

推荐答案

我只是在这里查看 __code__ 对象,所以我不能说这肯定有效,但是在我看来,您可以使用 co_names 元组来(递归地)遍历以特定函数为根的调用图,以便构建函数的传递闭包的某种散列可能被称为.(我认为不可能只包含为特定输入调用的函数,但您可以保守一点并包含所有可能的调用.)

I'm just poking around at the __code__ object here, so I can't say that this would work for sure, but it looks to me like you could use the co_names tuple to (recursively) traverse the call graph rooted at a particular function, in order to build up some sort of hash of the transitive closure of the functions that could possible be called. (I don't think it'd be possible to include only the functions that will be called for a particular input, but you could be conservative and include every possible call.)

为此,您需要维护某种符号表,以便能够查找被调用函数的名称.但是一旦你开始沿着这条路走下去,你似乎基本上要建立自己的 AST 等价物.那么,为什么不直接使用 AST 开始呢?

To do this you'd need to maintain some sort of symbol table to be able to look up the names of the functions that get called. But once you start going down this path, it seems like you're basically going to build up your own equivalent of the AST. So, why not just use the AST to start with ?

这篇关于如何检查 python 函数是否更改(在实时代码中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆