Monday, October 8, 2012

python how to know if variable is sequence type

1
python how to know if variable is sequence type

http://stackoverflow.com/questions/2184955/test-if-a-variable-is-a-list-or-tuple


Better still is:
isinstance(var, basestring)



2
python how to check for string types


One more note: in this case, you may actually want to use
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).
Alternatively, isinstance accepts a tuple of classes. This will return True if x is an instance of any subclass of any of (str, unicode):
isinstance(o, (str, unicode))



3
http://www.siafoo.net/article/56



Type Checking in Python




Apparently, type is completely useless for both type printing and type comparisons, as it can't understand old-style classes while __class__ can.
__class__ is messy, but is the only method that both works for both types of classes and will print out the name of the class if desired. It is the best choice for debugging, when you have no idea what type of object you're looking at.
isinstance also works on all objects. It also has another couple of perks: it actually checks to see if your object is an instance of a class or subclass of the class you pass it. Generally if you're type-checking you're interested in the existence of a behavior or method, and all subclasses of the target class will probably have it. So, isinstance is more accurate. Additionally, you can pass it a tuple of classes, and it will check against all of them. These perks make it the best choice for legitimate type-checking in a real program.
Here's a summary of what we found:
MethodWorks on old-style classes?Need to know type before calling?Best For
typeNoNoNothing, really
isinstanceYesYesLegitimate type-checking: When you're checking type against a known class
__class__YesNoDebugging: When you have no idea what class the instance is









No comments:

Post a Comment