Search code examples
pythonpython-3.xpython-click

passing values across functions yields no output


I have the code below where I use python package click to fetch some input from user. I then pass the user input to a function that has code to load a pre-trained model. I return a list of values that I pass to a second function that generates text using the model and other values. However the values aren't passed from first function to the second because when I try to print the list I get nothing. Could someone point out what I'm doing wrong, thanks a lot!!

@click.argument('email_template', nargs=1)
def load_model(email_template):
    ## code block here
    list1 = [email_template, value1, value2]
    return list1


def generate_text(value2):
    # code block here
    return result

if __name__ == '__main__':
    list1 = load_model()
    list2 = generate_text(list1)
    print(list2)

Solution

  • You are missing a @click.command() decorator. It is not enough to use @click.argument(), then expect this to work. The @click.command()-decorated function becomes the entry point of your script, and should not be seen as something that'll return the user options.

    Also, if email_template is the only option your script takes and it expects just one value, there is no point in using nargs=1.

    So do this:

    import click
    
    @click.command()
    @click.argument('email_template')
    def load_model(email_template):
        ## code block here
        # This is your *main script function*.
    
        list1 = [email_template, value1, value2]
    
        # don't return, continue the work you need doing from here
        list2 = text_generator(list1)
        print(list2)
    
    def generate_text(result):
        # code block here
        return value2
    
    if __name__ == '__main__':
        load_model()
    

    When load_model exits, your script exits.

    Also, rather than use print(), consider using click.echo(), especially when you need to print text that uses non-ASCII characters and needs to work on a variety of platforms, or if you want to include ANSI colors in your output.