PDA

View Full Version : [SOLVED] help in python with "if .. is" and "if .. in"



giuspen
December 20th, 2008, 01:24 AM
if I write the following code:


for dirpath, dirnames, filenames in os.walk(self.pyextensions_dir):
for filename in filenames:
print os.path.splitext(filename)[1]
if os.path.splitext(filename)[1] is '.py':
print filename

it doesn't works, otherwise if I write like this it works:
(just changed "if .. is" with "if .. in")


for dirpath, dirnames, filenames in os.walk(self.pyextensions_dir):
for filename in filenames:
print os.path.splitext(filename)[1]
if os.path.splitext(filename)[1] in ['.py']:
print filename
anybody can help me?
I would like to use "is" or "==" but doesn't works and I really don't understand why.

mssever
December 20th, 2008, 01:37 AM
if I write the following code:


for dirpath, dirnames, filenames in os.walk(self.pyextensions_dir):
for filename in filenames:
print os.path.splitext(filename)[1]
if os.path.splitext(filename)[1] is '.py':
print filenameit doesn't works, otherwise if I write like this it works:
(just changed "if .. is" with "if .. in")


for dirpath, dirnames, filenames in os.walk(self.pyextensions_dir):
for filename in filenames:
print os.path.splitext(filename)[1]
if os.path.splitext(filename)[1] in ['.py']:
print filenameanybody can help me?
I would like to use "is" or "==" but doesn't works and I really don't understand why.

if os.path.splitext(filename)[1] == '.py':works for me. Unless you provide the error, and/or describe exactly what happens, it's hard to know what's wrong.

EDIT: Here are some tests to prove my point:
>>> import os
>>> filename = '/sffd/fds.py'
>>> os.path.splitext(filename)[1]
'.py'
>>> '.py' == os.path.splitext(filename)[1]
True
>>> '.py' is os.path.splitext(filename)[1]
False
>>>

giuspen
December 20th, 2008, 01:42 AM
yes now I tried with '==' and it works, I thought that it was absolutely the same as 'is' but I was wrong, because 'is' doesn't work.
thanks, regards.

ghostdog74
December 20th, 2008, 02:10 AM
the "is" operator checks whether objects are the same, not just equal. "in" and "is" are different.

nvteighen
December 20th, 2008, 11:56 AM
is checks if two object's id() are the same.