correct way to detect container type

Aaron Bingham bingham at cenix-bioscience.com
Thu Oct 7 05:58:49 EDT 2004


Carlos Ribeiro wrote:

>On Thu, 07 Oct 2004 10:30:22 +0100, Robin Becker <robin at reportlab.com> wrote:
>  
>
>>I seem often to allow list/tuple arguments to be a singleton. This leads to code
>>of the form
>>
>>if type(arg) not in (type(()),type([])): arg = [arg]
>>
>>or alternatively
>>
>>from type import ListType, TupleType
>>_seqTypes = ListType, TupleType
>>......
>>if type(arg) not in _seqTypes: ....
>>
>>is there a 'best' way to do this?
>>    
>>
>
>Depending upon the way you're using your sequence types, why don't you
>check for __getitem__? As far as I'm aware, it's all that is needed to
>support for loops. In some cases __len__ may also be needed. The
>advantage is that you will accept any user defined type that supports
>the sequence interface.
>
>
>  
>
Careful! If all you are doing is:

for x in arg:
do something with x

Then arg only needs to support __iter__ and need not be a sequence type 
nor support __getitem__.

Aaron




More information about the Python-list mailing list