Search code examples
pythonfirst-class-functions

Making a first-class Function with arguments in Python


My issue is simple: I want to make a first-class function in python that has some arguments in it. But the problem is that to assign it, you need to call it, wich can be problematic

def print_double(num):
    print(num*2)
a = print_double(4)

I don't want to call it when I assign it, I would like to call it when I need it. Something like:

a()
>>> 8

Is there any way I can do it?


Solution

  • As written, your code would throw an error - NoneType is not callable.

    To do what you've shown, you'd need to curry the function

    def print_double(num):
        def inner():
           print(num*2)
        return inner 
    
    a = print_double(4)
    a()  # 8