eozzy
eozzy

Reputation: 68790

How to test type of an object in Python?

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?

Upvotes: 3

Views: 421

Answers (4)

Ben James
Ben James

Reputation: 125327

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.

Upvotes: 2

Skilldrick
Skilldrick

Reputation: 70889

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

Upvotes: 0

SilentGhost
SilentGhost

Reputation: 320019

use:

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

is intended for identity testing.

Upvotes: 3

Steven Kryskalla
Steven Kryskalla

Reputation: 14669

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.

Upvotes: 4

Related Questions