code: def sort_length(source_file, source_file_type, direction=1):
      
      direction_text = 'ascending' if direction == 1 else 'descending'
  
      logging.info('Indexing sequences by length: %s', direction_text)
  
      # Adapted from the Biopython tutorial example.
  
      # Get the lengths and ids, and sort on length
      len_and_ids = sorted((len(rec), rec.id)
                           for rec in SeqIO.parse(source_file, source_file_type))
  
      if direction == 0:
          ids = reversed([seq_id for (length, seq_id) in len_and_ids])
      else:
          ids = [seq_id for (length, seq_id) in len_and_ids]
      del len_and_ids  # free this memory
  
      # SeqIO.index does not handle gzip instances
      if isinstance(source_file, gzip.GzipFile):
          tmpfile = tempfile.NamedTemporaryFile()
          source_file.seek(0)
          tmpfile.write(source_file.read())
          tmpfile.seek(0)
          source_file = tmpfile
  
      record_index = SeqIO.index(source_file.name, source_file_type)
  
      for seq_id in ids:
          yield record_index[seq_id]
docs: Sort sequences by length. 1 is ascending (default) and 0 is descending.