Basically I want to do this:
obj = \'str\'
type ( obj ) == string
I tried:
type ( obj ) == type ( string )
<
First, avoid all type comparisons. They're very, very rarely necessary. Sometimes, they help to check parameter types in a function -- even that's rare. Wrong type data will raise an exception, and that's all you'll ever need.
All of the basic conversion functions will map as equal to the type function.
type(9) is int
type(2.5) is float
type('x') is str
type(u'x') is unicode
type(2+3j) is complex
There are a few other cases.
isinstance( 'x', basestring )
isinstance( u'u', basestring )
isinstance( 9, int )
isinstance( 2.5, float )
isinstance( (2+3j), complex )
None, BTW, never needs any of this kind of type checking. None is the only instance of NoneType. The None object is a Singleton. Just check for None
variable is None
BTW, do not use the above in general. Use ordinary exceptions and Python's own natural polymorphism.
For other types, check out the types module:
>>> import types
>>> x = "mystring"
>>> isinstance(x, types.StringType)
True
>>> x = 5
>>> isinstance(x, types.IntType)
True
>>> x = None
>>> isinstance(x, types.NoneType)
True
P.S. Typechecking is a bad idea.
You're very close! string
is a module, not a type. You probably want to compare the type of obj
against the type object for strings, namely str
:
type(obj) == str # this works because str is already a type
Alternatively:
type(obj) == type('')
Note, in Python 2, if obj
is a unicode type, then neither of the above will work. Nor will isinstance()
. See John's comments to this post for how to get around this... I've been trying to remember it for about 10 minutes now, but was having a memory block!
Use isinstance(object, type)
. As above this is easy to use if you know the correct type
, e.g.,
isinstance('dog', str) ## gives bool True
But for more esoteric objects, this can be difficult to use. For example:
import numpy as np
a = np.array([1,2,3])
isinstance(a,np.array) ## breaks
but you can do this trick:
y = type(np.array([1]))
isinstance(a,y) ## gives bool True
So I recommend instantiating a variable (y
in this case) with a type of the object you want to check (e.g., type(np.array())
), then using isinstance
.
I use type(x) == type(y)
For instance, if I want to check something is an array:
type( x ) == type( [] )
string check:
type( x ) == type( '' ) or type( x ) == type( u'' )
If you want to check against None, use is
x is None
i think this should do it
if isinstance(obj, str)