13

What's the difference between:

isinstance(foo, types.StringType)

and

isinstance(foo, basestring)

?

Jean-François Corbett
  • 37,420
  • 30
  • 139
  • 188
YGA
  • 9,546
  • 15
  • 47
  • 50

5 Answers5

18

For Python2: basestring is the base class for both str and unicode, while types.StringType is str. If you want to check if something is a string, use basestring. If you want to check if something is a bytestring, use str and forget about types.

Eldamir
  • 9,888
  • 6
  • 52
  • 73
Lukáš Lalinský
  • 40,587
  • 6
  • 104
  • 126
10

This stuff is completely different in Python3

types not longer has StringType
str is always unicode
basestring no longer exists

So try not to sprinkle that stuff through your code too much if you might ever need to port it

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1
>>> import types
>>> isinstance(u'ciao', types.StringType)
False
>>> isinstance(u'ciao', basestring)
True
>>> 

Pretty important difference, it seems to me;-).

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
0

If you need to write code that works in both Python 2 and Python 3 you can use install future via pip install future and import from past.builtins import basestring.

from past.builtins import basestring

See https://python-future.org/compatible_idioms.html#strings-and-bytes

cycgrog
  • 21
  • 3
0

For Python 2.x:

try:
    basestring        # added in Python 2.3
except NameError:
    basestring = (str, unicode)
...
if isinstance(foo, basestring):
    ...

Of course this might not work for Python 3, but I'm quite sure the 2to3 converter will take care of the topic.

Tobias
  • 2,481
  • 3
  • 26
  • 38