Test for structure

Ben Finney bignose-hates-spam at and-benfinney-does-too.id.au
Wed Feb 16 19:39:00 EST 2005


alex wrote On 17/02/05 02:08:
> how can I check if a variable is a structure (i.e. a list)? For my 
> special problem the variable is either a character string OR a list 
> of character strings line ['word1', 'word2',...]

You're trying to apply the LBYL principle.  My bet is that your "special
problem" can be solved by the EAFP principle.  (These terms are
explained in the Glossary of the tutorial,
<http://www.python.org/doc/current/tut/node18.html>.)

If you test for a specific set of types, your code will not work with
types that you have not considered yet behave like lists.  As you 
discover more object types that you want the code to work with, it will 
sprout more cruft for checking those types.

If you want to use some list behaviour of the object, don't check first.
Use it, and catch the TypeError exception in the event that it's not.
This way, *any* object that implements the functionality you need will
work, regardless of its type.



More information about the Python-list mailing list