[Biopython-dev] Basic python question with regard to Unigene parser

Jim Balhoff james.balhoff at duke.edu
Thu Oct 26 13:46:34 UTC 2006


Hi Sean,

On Oct 26, 2006, at 8:30 AM, Sean Davis wrote:

> On Thursday 26 October 2006 08:09, Sean Davis wrote:
>> Let me start off by saying that I am a python newbie after working  
>> in perl
>> for the last few years.  I am working on a Unigene flat file  
>> parser.  In my
>> scanner, I have a construct that looks like:
>>
>>         for line in handle:
>>             tag = line.split(' ')[0]
>>             line = line.rstrip()
>>             if tag=='ID':
>>                 consumer.ID(line)
>>             if tag=='GENE':
>>                 consumer.GENE(line)
>>             if tag=='TITLE':
>>                 consumer.TITLE(line)
>>             if tag=='EXPRESS':
>>                 consumer.EXPRESS(line)
>>             ....
>>
>> Since I am setting things up so that there is a 1:1 correspondence  
>> between
>> the "tag" and the consumer method, is there an easy way to reduce  
>> this long
>> set of IF statements to a simple mapping procedure that maps a tag  
>> to the
>> correct method?
>>
>> Sorry for the naive question....
>
> Even more apologies.  I answered my own question.  Something like  
> this seems
> to work:
>
> 	exec('consumer.'+tag+'(line)')
>
> which replaces all the IF statements quite nicely.

Alternatively, you may want to look at getattr().  There is a good  
description here:

<http://diveintopython.org/power_of_introspection/getattr.html#d0e9362>

Jim




More information about the Biopython-dev mailing list