Python Forum
Creating a variable as a function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Creating a variable as a function
#5
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:
# Correct:
def f(x):
    return 2*x

# Wrong:
f = lambda x: 2*x
the first form means that the name of the resulting function object is specifically 'f' instead of the generic '<lambda>'. This is more useful for tracebacks and string representations in general. The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (i.e. that it can be embedded inside a larger expression)

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))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
RE: Creating a variable as a function - by buran - Sep-06-2020, 05:08 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable for the value element in the index function?? Learner1 8 668 Jan-20-2024, 09:20 PM
Last Post: Learner1
  Variable is not defined error when trying to use my custom function code fnafgamer239 4 602 Nov-23-2023, 02:53 PM
Last Post: rob101
  Printing the variable from defined function jws 7 1,334 Sep-03-2023, 03:22 PM
Last Post: deanhystad
  Function parameter not writing to variable Karp 5 951 Aug-07-2023, 05:58 PM
Last Post: Karp
  Retrieve variable from function labgoggles 2 1,056 Jul-01-2022, 07:23 PM
Last Post: labgoggles
  Cant transfer a variable onto another function KEIKAS 5 1,906 Feb-09-2022, 10:17 PM
Last Post: deanhystad
  Please explain uncommon way of declaring and using variable [function.variable] esphi 4 2,343 Nov-07-2020, 08:59 AM
Last Post: buran
  Spyder Quirk? global variable does not increment when function called in console rrace001 1 2,237 Sep-18-2020, 02:50 PM
Last Post: deanhystad
  passing variable to function Rejoice 4 2,886 Sep-11-2020, 03:27 AM
Last Post: Pleiades
  [split] Creating a variable as a function DPaul 23 6,747 Sep-07-2020, 05:20 PM
Last Post: DPaul

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020