Python与Julia的`@edit`宏的等价物是什么?

2024-05-10 21:43:17 发布

您现在位置:Python中文网/ 问答频道 /正文

在Julia中,从REPL调用带有^{}宏的函数将打开编辑器,并将光标放在定义方法的行上。因此,这样做:

julia> @edit 1 + 1

跳转到julia/base/int.jl并将光标放在行上:

(+)(x::T, y::T) where {T<:BitInteger} = add_int(x, y)

就像function formedit(+, (Int, Int))

Python中是否有一个等效的decorator/函数从Python REPL执行相同的操作


Tags: 函数base编辑器whererepleditint行上
2条回答

在大多数IDE(如PyCharm或VSCode)中,您可以按住Ctrl键并单击某个函数/类以获取其定义,即使它是在核心语言或第三方库中(在VSCode中,这也适用于Julia btw)

一个限制是,这只适用于“纯Python”代码、C库代码等。未显示

免责声明:在Python生态系统中,这不是核心语言/运行时的工作,而是IDE等工具的工作。例如,ipython shell^{} special syntax来获得改进的帮助,包括源代码

Python 3.8.5 (default, Jul 21 2020, 10:42:08)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.18.1   An enhanced Interactive Python. Type '?' for help.

In [1]: import random

In [2]: random.uniform??
Signature: random.uniform(a, b)
Source:
    def uniform(self, a, b):
        "Get a random number in the range [a, b) or [a, b] depending on rounding."
        return a + (b-a) * self.random()
File:      /usr/local/Cellar/python@3.8/3.8.5/Frameworks/Python.framework/Versions/3.8/lib/python3.8/random.py
Type:      method

Python运行时本身允许通过^{}查看对象的源代码。这使用启发式搜索可用的源代码;对象本身不携带其源代码

Python 3.8.5 (default, Jul 21 2020, 10:42:08)
[Clang 11.0.0 (clang-1100.0.33.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import inspect
>>> print(inspect.getsource(inspect.getsource))
def getsource(object):
    """Return the text of the source code for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a single string.  An
    OSError is raised if the source code cannot be retrieved."""
    lines, lnum = getsourcelines(object)
    return ''.join(lines)

无法将任意表达式或语句解析为其源代码;由于Python中的所有名称都是动态解析的,因此绝大多数表达式都没有定义良好的实现,除非执行。调试器(如^{}提供的调试器)允许在执行表达式时检查表达式

相关问题 更多 >