在Python中获取包含一行的函数
我希望做某种反射,给定行号和模块,我得到包含该行的模块中的函数名称。这在Python中可能吗?
I wish to do some kind of reflection thing where given a line number and a module, I get back the name of the function in that module containing that line. Is this possible in Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
python 中没有内置方法可以执行此操作。但是,您可以定义一个函数来执行类似的操作,但它会将模块作为当前目录中的文件进行处理:
该函数打开作为文件传递的模块,迭代直到到达传递的行,然后搜索使用正则表达式的函数。如果传递的行上没有声明函数或者传递的行超出了文件的行数,则会引发
错误
。例如:There is no built-in way to do this in python. However, you could define a function to do something like that, but it would handle modules as files in your current directory:
This function is opening the module passed as a file, iterating until reached the passed line, and then, searching the name of the function using regular expressions. If there was no function declared on the passed line or the line passed exceeded the number of lines of the file, it will raise an
Error
. E.g.: