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 os.unlink false >>> os.remove == os.unlink true 

why that? isn't os.unlink supposed alias of os.remove?

to answer question have dive bit details of how python interpreter works. might different in other python implementations.

first let's start os.remove , os.unlink functions defined. in modules/posixmodule.c registered as:

{"unlink",          posix_unlink, meth_varargs, posix_unlink__doc__}, {"remove",          posix_unlink, meth_varargs, posix_remove__doc__}, 

note function pointers both point posix_unlink in ml_meth member.

for method objects, == equality operator implemented meth_richcompare(...) in objects/methodobject.c.

it contains logic, explains why == operator returns 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 null eq starts out true. compare function pointers in ml_meth (the same posix_unlink referenced struct above) , since match eq remains true. end result python returns true.

the is operator simpler , stricter. is operator compares pycfunctionobj* pointers. different -- came different structs , distinct objects, is operator return false.

the rationale separate functions objects (recall docstrings different) point same implementation, difference in behavior between is , == justifiable.

is brings stronger guarantee, , meant fast , cheap (a pointer comparison, essentially). == operator inspects object , returns true when content matches. in context, function pointer content.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -