python - Test if a variable is a list or tuple -
In Python, what is the best way to check if any variable is a list or a tuple? (I.e. archive)
What has been suggested here as evil?
Update: The most common reason I want to separate a list from the string is when I have a data-structure of lists of lists of lists of lists of lists of lists of dark nested trees / strings that are indefinitely Searching with a recursive algorithm and I should know how I pressed the "leaf" nodes.
Go further and use isinstance
Bad as long as it contains custom sequences, iterators, and other things you really might need. However, sometimes you need to behave differently, for example, if a string passes clearly for my preference like str
or Unicode
Look for the form:
Installing import types (var, types.StringTypes)
for NB types.StringType
Do not mistake for types.StringTypes
. Later, the str
and Unicode
objects are included.
The module is considered by many to be simply obsolete in favor of the object, directly checking against the type of object, so if you do not want to use the above, you can optionally str You can clearly test from
and
Unicode
in this way:
isinstance (var, (str, unicode)):
Edit:
Better still:
isinstance (var, basestring)
< / Pre>End Edit
In After any one of you, behave like you are getting a general sequence, non-sequences raise the appropriate exception.
Check that the "evil" type is not about examining that you want to behave differently for a certain type of thing, that is, you artificially unexpected object Restricted from doing the right thing with the types that otherwise would do the right thing if you have the last fallback which is not type-checked, then you remove this restriction. It should be noted that a lot of type of investigation is a code odor that indicates that you want to do some refactoring, but that does not mean that you should avoid it.
Comments
Post a Comment