About the str class

Can I use isinstance(something, str) to decide whether “something” is a string. I have just read in one book that said this is wrong, but I do not know why. Any reviews will be highly appreciated.

Yes, you can use isinstance(something, str) to decide whether something` is a string.

I don’t know why the book says it is wrong. Do they give a reason?

Perhaps it’s because it could be a subclass of str?

1 Like

Hi Robert,

I guess your book was written in PY2’s time?
You can use isinstance(something, str) in PY3 but isinstance(something, (str, unicode)) in PY2, or isinstance(something, six.string_types) if you want to keep compatibility with PY2x3.

Unicode string unicode str
Bytes string str(=bytes) bytes

Which would normally be just fine, and is a primary reason why
isinstance is strongly recommended over, say type(thing) is str.
They mean different things, and you should write what you mean. But
usually in Python we want to know “can I use it like a str?”, and
isinstance is the better choice.

Cameron Simpson cs@cskk.id.au

isinstance works correctly when it comes to subclasses.

If B is a subclass of A, then instances of B are also considered instances of A. That’s part of the definition of subclassing :slight_smile:

To be concrete:

class MyString(str):

s = MyString()
assert isinstance(s, str)

The alternatives I can think of are:

  • type(s) is str which can be used to test that s is a direct instance of str, not a subclass;
  • duck-typing and EAFP;
  • perhaps the book is thinking about wanting to handle bytes and strings together?
  • or is thinking about UserString.

Without knowing what the book says, we’re just guessing.

1 Like

That was my point, whether it’s a string of class str exactly and not of a subclass.

About the str class - #4 by komoto48g MyString(str):

s = MyString()
assert isinstance(s, str)