一个带有pass语句的Python函数

5
在很多代码中,我看到了一些在类中定义了函数,但只是使用pass语句并附带一些注释。就像Python中的本机内置函数一样:
def copyright(*args, **kwargs): # real signature unknown
"""
interactive prompt objects for printing the license text, a list of
    contributors and the copyright notice.
"""
pass

我知道 `pass` 什么也不做,这有点冷漠和无用,还有 `null` 表达式,但为什么程序员会使用这样的函数?
此外,还有一些函数使用 `return ""` ,比如:
def bin(number): # real signature unknown; restored from __doc__
"""
bin(number) -> string

Return the binary representation of an integer.

   >>> bin(2796202)
   '0b1010101010101010101010'
"""
return ""

为什么程序员使用这些东西?
2个回答

6
你的集成开发环境(IDE)是在欺骗你。那些函数实际上并不是那样的;你的IDE编造了一堆几乎与真实代码没有任何相似之处的虚假源代码。这就是为什么它会显示像“# real signature unknown”这样的东西。我不知道他们为什么认为这是个好主意。
真正的代码看起来完全不同。例如,这里是真正的bin(Python 2.7版本):
static PyObject *
builtin_bin(PyObject *self, PyObject *v)
{
    return PyNumber_ToBase(v, 2);
}

PyDoc_STRVAR(bin_doc,
"bin(number) -> string\n\
\n\
Return the binary representation of an integer or long integer.");

它是用C语言编写的,并作为一个简单的包装器实现,围绕C函数PyNumber_ToBase
PyObject *
PyNumber_ToBase(PyObject *n, int base)
{
    PyObject *res = NULL;
    PyObject *index = PyNumber_Index(n);

    if (!index)
        return NULL;
    if (PyLong_Check(index))
        res = _PyLong_Format(index, base, 0, 1);
    else if (PyInt_Check(index))
        res = _PyInt_Format((PyIntObject*)index, base, 1);
    else
        /* It should not be possible to get here, as
           PyNumber_Index already has a check for the same
           condition */
        PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
                        "int or long");
    Py_DECREF(index);
    return res;
}

我想JetBrains(就是他们)这样做是为了让你可以浏览库模块,最终到达一个有文档支持的死胡同,而不是只是不允许你跟随名称到其定义。 - Peter Wood
这很奇怪,似乎值得提交一个错误报告。 - Chris_Rands

3

这是一个待完成的事情标记(TBD),在IT技术中相关。你知道需要什么功能,知道该提供什么和返回什么,但现在还不打算编写它,因此你制作了一个“原型”。

有时,软件包会随带这些函数,因为它们期望你继承并重写它们。


3
一个合理的猜测,但真正的原因完全不同。请注意,这些是内置对象,例如内置的bin函数或存在的copyright对象,以便您可以在交互模式下键入copyright并获取版权消息。它们已经被实现了。 - user2357112

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接