E pur si muove

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.

Wednesday, February 10, 2010 | Labels: |


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)
>>> isinstance(1l, Integral)
>>> isinstance(1.1, Integral)

New comments are not allowed.

Subscribe to: Post Comments (Atom)