[英]In Python (2.7), why is os.remove not identical to os.unlink?
>>> import sys
>>> sys.version
'2.7.3 (default, Mar 13 2014, 11:03:55) \n[GCC 4.7.2]'
>>> import os
>>> os.remove is os.unlink
False
>>> os.remove == os.unlink
True
Why is that? 这是为什么? Isn't os.unlink supposed to be an alias of os.remove?
是不是os.unlink应该是os.remove的别名?
To answer this question we have to dive a bit into the details of how the python interpreter works. 要回答这个问题,我们必须深入了解python解释器的工作原理。 It might be different in other python implementations.
在其他python实现中可能会有所不同。
First let's start where the os.remove
and os.unlink
functions are defined. 首先让我们从定义
os.remove
和os.unlink
函数开始。 In Modules/posixmodule.c they are registered as: 在Modules / posixmodule.c中,它们注册为:
{"unlink", posix_unlink, METH_VARARGS, posix_unlink__doc__},
{"remove", posix_unlink, METH_VARARGS, posix_remove__doc__},
Note that the function pointers both point to posix_unlink
in their ml_meth
member. 需要注意的是函数指针都指向
posix_unlink
他们ml_meth
成员。
For method objects, the ==
equality operator is implemented by meth_richcompare(...)
in Objects/methodobject.c . 对于方法对象,
==
equality运算符由Objects / methodobject.c中的 meth_richcompare(...)
实现 。
It contains this logic, which explains why the ==
operator returns True
. 它包含这个逻辑,它解释了为什么
==
运算符返回True
。
a = (PyCFunctionObject *)self;
b = (PyCFunctionObject *)other;
eq = a->m_self == b->m_self;
if (eq)
eq = a->m_ml->ml_meth == b->m_ml->ml_meth;
For built-in functions m_self
is NULL
so eq
starts out true
. 对于内置函数,
m_self
为NULL
因此eq
开始为true
。 We then compare the function pointers in ml_meth
(the same posix_unlink
referenced from the struct above) and since they match eq
remains true
. 然后我们比较
ml_meth
的函数指针(从上面的结构引用的相同posix_unlink
),因为它们匹配eq
保持为true
。 The end result is that python returns True
. 最终结果是python返回
True
。
The is
operator is simpler and stricter. 该
is
操作更简单和更严格。 The is
operator only compares the PyCFunctionObj*
pointers. is
运算符仅比较PyCFunctionObj*
指针。 They will be different -- they came from different structs and are distinct objects, so the is
operator will return False
. 它们将是不同的 - 它们来自不同的结构并且是不同的对象,因此
is
运算符将返回False
。
The rationale is likely that they are separate functions objects (recall their docstrings are different) but they point to the same implementation, so the difference in behavior between is
and ==
is justifiable. 基本原理可能是它们是单独的函数对象(回想一下它们的文档字符串是不同的)但它们指向相同的实现,因此
is
和==
之间的行为差异是合理的。
is
brings a stronger guarantee, and is meant to be fast and cheap (a pointer comparison, essentially). is
一个更强大的保证,并且意味着快速和廉价(指针比较,基本上)。 The ==
operator inspects the object and returns True
when its content matches. ==
运算符检查对象,并在其内容匹配时返回True
。 In this context, the function pointer is the content. 在此上下文中,函数指针是内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.