def _maybe_add_read_preference(spec, read_preference):
 mode = read_preference.mode
 tag_sets = read_preference.tag_sets
 max_staleness = read_preference.max_staleness
 if (mode and ((mode != ReadPreference.SECONDARY_PREFERRED.mode) or (tag_sets != [{}]) or (max_staleness != (-1)))):
  if ('$query' not in spec):
   spec = SON([('$query', spec)])
  spec['$readPreference'] = read_preference.document
 return spec

def _maybe_add_read_preference ( spec , read_preference ) : mode = read_preference . mode tag_sets = read_preference . tag_sets max_staleness = read_preference . max_staleness if ( mode and ( ( mode != ReadPreference . SECONDARY_PREFERRED . mode ) or ( tag_sets != [ { } ] ) or ( max_staleness != ( - 1 ) ) ) ) : if ( '$query' not in spec ) : spec = SON ( [ ( '$query' , spec ) ] ) spec [ '$readPreference' ] = read_preference . document return spec
add $readpreference to spec when appropriate .