Search code examples
pythonfunctionsnakemake

Access specific element of a list returned by a function in Snakemake


In my Snakemake workflow, I have defined a function that uses a file produced previously during the workflow, parses it and returns a list of 2 elements, for example :

def get_param_value(wildcards) :
    # do stuff with the wildcards and some files
    return ["element1","element2"]

I would then like to use each value of the returned list as independent params in a subsequent rule, such as :

rule example :
    input :
        'input_file.txt'
    output :
        'output_file.txt'
    params :
        param1 = "element1", # First element of the list returned by get_param_value function
        param2 = "element2" # Second element of the list returned by get_param_value function
    shell :
        'somecommand -i {input} -smth1 {params.param1} -smth2 {params.param2} -o {output} ;'

I have tried using the function directly in the rule, with

params :
    param1 = get_param_value[0],
    param2 = get_param_value[1]

but I get a TypeError : 'function' object is not subscriptable (which is expected because it's a function).

Do you have a workaround for this ?


Solution

  • After a bit of tinkering and thanks to Mario Abbruscato's suggestions, this did the trick : I used lambda functions in the params directive of the rule to extract the elements of the list and assign them to different parameters :

    rule example :
        input :
            'input_file.txt'
        output :
            'output_file.txt'
        params :
            params = lambda wildcards : get_param_value(wildcards)
        shell :
            'somecommand -i {input} -smth1 {params.param1[0]} -smth2 {params.param2[1]} -o {output} ;'