0

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?

Stepa1411
  • 27
  • 3
  • Can you clarify your question, please? What a problem to store your print_double() at a separate module and do "module import print_double as a" ? – Bohdan Jul 30 '22 at 18:26
  • All Python functions are first-class. That's the wrong terminology. It looks like you want to write a function that returns another function (a [closure](https://en.wikipedia.org/wiki/Closure_(computer_programming))), or maybe you're actually looking for a [partial](https://docs.python.org/3/library/functools.html#partial-objects) -- it's not totally clear. – wjandrea Jul 30 '22 at 18:34
  • Better link: [`partial`](https://docs.python.org/3/library/functools.html#functools.partial) – wjandrea Jul 30 '22 at 18:44

1 Answers1

2

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
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245