Creating a variable as a function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Creating a variable as a function (/thread-29495.html) |
Creating a variable as a function - JarredAwesome - Sep-05-2020 In JavaScript there is an ability to make a variable a function. Does that exists in python? For example, could I do something like this? Def x(y): print(y) z= def x(‘hello’) Z()Thanks! RE: Creating a variable as a function - bowlofred - Sep-05-2020 You can't make anonymous functions, you have to give them a name. So in line 1, your function has the name x . Once it has a name, you can assign it another name as well and call it that way. In line 4, you're not just creating a function, you're trying to create a function with some private data (a closure). Yes, you can create such functions and return them. def x(y): print(y) def z(): x("hello") z() new_name = z new_name() Or a better example of a closure:def make_printer(data): def printer_func(): print(data) return printer_func myhello = make_printer("Hello, world.") myhello()
RE: Creating a variable as a function - JarredAwesome - Sep-05-2020 Anonymous Functions! It was driving me crazy trying to remember what they were called. Thanks! That really makes things easier for me! RE: Creating a variable as a function - bowlofred - Sep-05-2020 I guess to say "can't" is a little bit strong. Python does have lambda expressions, but they can only be a single expression rather than everything that can be placed into a (named) function. >>> squareit = lambda x: x**2 # no name, but assigned to squareit >>> print(squareit(5)) 25But because of the limitations, I think of them as a separate category from python functions. RE: Creating a variable as a function - buran - Sep-06-2020 The suggestion with lambda goes against PEP8 recommendations: Quote:Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier: as to OP question - function is object as any other, you can always assign the function to variable: def spam(): print('This is spam') eggs = spam eggs()This has plenty of useful applications, e.g. the pythonic way to create a menu/switch statement, using dict with functions as values. also, you may be interested in functools.partial from functools import partial def raise_power(num, power): return num ** power power_3 = partial(raise_power, power=3) print(power_3(2)) |