Discovering basestring
Wednesday, February 10, 2010
This may seem simple and trivial, but today I discovered the basestring
type in Python. It is essentially a base type for str
and unicode
, which comes in handy when writing isinstance(foo, basestring)
in test code for example.
Strangely, despide PEP 237 mentioning the equivalent for int
and long
as "integer
" I can't actually find what has become of that, so still writing isinstance(foo, (int, long))
for now.
Note that this is Python 2.x only, in 3.x it's all unicode so there is no longer a need for a common base type. int
and long
are unified as well in Python 3.x obviously.
2 comments:
Anonymous said...
import __builtin__
__builtin__.baseint = int, long
assert isinstance(1, baseint)
assert isinstance(1L, baseint)
assert isinstance(False, baseint)
Anonymous said...
Starting from python 2.6 you can use the numbers module.
>>> from numbers import Integral
>>> isinstance(1, Integral)
True
>>> isinstance(1l, Integral)
True
>>> isinstance(1.1, Integral)
False
New comments are not allowed.