1

Here is my current code:

def hypergeometric(query_genes, filename, input_format):

    if input_format == 'ENSEMBLID':
        OCRs = OpenChromatinRegion.query
                .filter(OpenChromatinRegion.filename == filename)
                .filter(OpenChromatinRegion.ENSEMBLID.in_(query_genes))
                .filter(OpenChromatinRegion.ENSEMBLID != 'NA')
                .all()

    elif input_format == 'gene_symbol':
        OCRs = OpenChromatinRegion.query
                .filter(OpenChromatinRegion.filename == filename)
                .filter(OpenChromatinRegion.gene_symbol.in_(query_genes))
                .filter(OpenChromatinRegion.gene_symbol != 'NA')
                .all()

For obvious reasons, this is very painful. Is there some way of interpolating the input_format variable into the query?

1 Answer 1

2

You can simply extract the required attribute using getattr and use it in filter.

def hypergeometric(query_genes, filename, input_format):

     input_format_attribute = getattr(OpenChromatinRegion, input_format, None)     
     if input_format_attribute is not None:
        OCRs = OpenChromatinRegion.query
                .filter(OpenChromatinRegion.filename == filename)
                .filter(input_format_attribute.in_(query_genes))
                .filter(input_format_attribute != 'NA')
                .all() 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.