简体   繁体   English

在Python(2.7)中,为什么os.remove与os.unlink不相同?

[英]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.removeos.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_selfNULL因此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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM