tags:

views:

93

answers:

4
import string
print string.ascii_lowercase # abcdefghijklmnopqrstuvwxyz
print type(string.ascii_lowercase) # <type 'str'>
print string.ascii_lowercase is str # False

Shouldn't it be True?

+2  A: 

string.ascii_lowercase is str should not be True.

type(string.ascii_lowercase) is str is True.

The is keyword checks object identity, not type.

You may have seen code like foo is None often and thought that None is a type. None is actually a singleton object.

Ben James
Oh, why not? any technical reason that I must know?
Nimbuz
because `string.ascii_lowercase` is a string, whereas `str` is a type.
Skilldrick
`is` test's whether they are the same object. i.e. they are both pointers to an object, are those objects the same.
James Brooks
See what happens when you do `type(str)`
Skilldrick
+4  A: 

The is operator compares the identity of two objects. This is what I believe it does behind the scenes:

id(string.ascii_lowercase) == id(str)

Actual strings are always going to have a different identity than the type str, so this will always be False.

Here is the most Pythonic way to test whether something is a string:

isinstance(string.ascii_lowercase, basestring)

This will match both str and unicode strings.

lost-theory
Thanks for the id() example, got it now! :)
Nimbuz
+2  A: 

use:

>>> isinstance('dfab', str)
True

is intended for identity testing.

SilentGhost
+1 http://docs.python.org/library/functions.html?highlight=isinstance#isinstance "Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof."
artlung
A: 

Don't you want type(string.ascii_lowercase) is str ?

Skilldrick