How can I extract the longest N isoforms per gene from a fasta file?
I know you are asking for a python solution. But maybe you are interested in other ways.

You can use samtools faidx to index your fasta file. The resulting file contains the information about the length of every sequence. We can sort by length and extract the first n transcripts per gene.

1. Index fasta

samtools faidx input.fa


2. Extract IDs of the n longest transcripts per gene

sed 's/_.\+//g' input.fa.fai | sort -u | 
    parallel -k 'grep {} -m 3 &lt;(sort -k2,2 -r --sort g input.fa.fai) |
        cut -f1' &gt; longestID.txt


The sed command replaces everything from _ onwards in each line, leaving behind only the gene name. sort -u is used to get a list of distinct gene names. For each of theses gene names we grep for the first 3 matches in the descending sorted by length index file. As we just want the sequence ids, we select only the first column with cut. Adopt the -m parameter if you want more or fewer transcripts.

3. Get sequences

samtools faidx input.fa -r longestID.txt &gt; output.fa