To check if o
is an instance of str
or any subclass of str
, use isinstance (this would be the "canonical" way):
if isinstance(o, str):
To check if the type of o
is exactly str
(exclude subclasses):
if type(o) is str:
The following also works, and can be useful in some cases:
if issubclass(type(o), str):
See Built-in Functions in the Python Library Reference for relevant information.
One more note: in this case, if you're using Python 2, you may actually want to use:
if isinstance(o, basestring):
because this will also catch Unicode strings (unicode
is not a subclass of str
; both str
and unicode
are subclasses of basestring
). Note that basestring
no longer exists in Python 3, where there's a strict separation of strings (str
) and binary data (bytes
).
Alternatively, isinstance
accepts a tuple of classes. This will return True
if o
is an instance of any subclass of any of (str, unicode)
:
if isinstance(o, (str, unicode)):
Best Answer
Not directly an answer to your question, but you should consider naming it
__version__
, notversion
.This is almost a quasi-standard. Many modules in the standard library use
__version__
, and this is also used in lots of 3rd-party modules, so it's the quasi-standard.Usually,
__version__
is a string, but sometimes it's also a float or tuple.Edit: as mentioned by S.Lott (Thank you!), PEP 8 says it explicitly:
You should also make sure that the version number conforms to the format described in PEP 440 (PEP 386 a previous version of this standard).