How to check object type 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?

+3
source share
4 answers

The operator iscompares the identity of two objects. Here is what I think is happening behind the scenes:

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

Actual strings will always have a different identity than the type str, so it will always be False.

Here is the most Pythonic way to check if something is a string:

isinstance(string.ascii_lowercase, basestring)

This will match the lines strand unicode.

+4
source

use:

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

isdesigned for identity testing.

+3
source

string.ascii_lowercase is str True.

type(string.ascii_lowercase) is str True.

is , .

, foo is None , None - . None - .

+2

type(string.ascii_lowercase) is str?

0

Source: https://habr.com/ru/post/1728821/


All Articles