在Python中获取包含一行的函数

发布于 2024-12-26 14:09:21 字数 54 浏览 1 评论 0原文

我希望做某种反射,给定行号和模块,我得到包含该行的模块中的函数名称。这在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沧桑㈠ 2025-01-02 14:09:21

python 中没有内置方法可以执行此操作。但是,您可以定义一个函数来执行类似的操作,但它会将模块作为当前目录中的文件进行处理:

import re

def get_function_name(module, line):
    module_file = module.replace('.', '/') + '.py'
    lines = open(module_file, 'r').xreadlines()
    i = line - 1
    try:
        while i:
            tmp = next(lines)
            i -= 1
    except StopIteration:
        raise EOFError('Not enought lines in module %s' % module)
    function_line = next(lines)
    function_name =  re.match('def (\w+)\([^)]*\):', function_line)
    if function_name:
        return function_name.group(1)
    raise ValueError('No function declared on line %s' % line)

该函数打开作为文件传递的模块,迭代直到到达传递的行,然后搜索使用正则表达式的函数。如果传递的行上没有声明函数或者传递的行超出了文件的行数,则会引发错误。例如:

>>> get_function_name('my_module.my_submodule', 24)
'my_function_name'
>>> get_function_name('my_module.my_submodule', 25)
    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 15, in get_function_name
ValueError: No function declared on line 17
>>> get_function_name('my_module.my_submodule', 123456)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 10, in get_function_name
EOFError: Not enought lines in module

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:

import re

def get_function_name(module, line):
    module_file = module.replace('.', '/') + '.py'
    lines = open(module_file, 'r').xreadlines()
    i = line - 1
    try:
        while i:
            tmp = next(lines)
            i -= 1
    except StopIteration:
        raise EOFError('Not enought lines in module %s' % module)
    function_line = next(lines)
    function_name =  re.match('def (\w+)\([^)]*\):', function_line)
    if function_name:
        return function_name.group(1)
    raise ValueError('No function declared on line %s' % line)

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.:

>>> get_function_name('my_module.my_submodule', 24)
'my_function_name'
>>> get_function_name('my_module.my_submodule', 25)
    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 15, in get_function_name
ValueError: No function declared on line 17
>>> get_function_name('my_module.my_submodule', 123456)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 10, in get_function_name
EOFError: Not enought lines in module
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文