Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
functions in a dictionary
#1
it has been said not to define functions by assigning a lambda. but i want to have a dictionary (or list as the use case may be) contain a bunch of functions (perhaps small ones). i see no easy way to do this with def:
def function_collection['foobah'](a): # invalid syntax
    return a*a+a
the only clean way looks like:
function_collection['foobah'] = lambda a:a*a+a
is this an OK exception?

yeah, i know you can do a def then assign that name to the dictionary item. but that just looks so ugly:
def foobah(a):
     return a*a+a
function_collection['foobah'] = foobah
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Quote:i know you can do a def then assign that name to the dictionary item. but that just looks so ugly
What does this mean? Python is a programming language so it is designed to perform tasks, not so it will be "pretty" according to one person's arbitrary viewpoint.
Reply
#3
i use "ugly" for programming code in a broader sense than just the opposite of "pretty". it also include "inelegant" and other bad things. i wanted to point out doing "def" followed by assigning its name to another. but it makes natural sense to me to assign a lambda to a variable and that's the name of the function. this is because some of the languages i have work with in the past did their functions that way. they just used "function" or some syntactic expression and not "lambda". i wanted to see if anyone disagreed with any part of that.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
Is this more like what you want?

function_dictionary = {'fun1':lambda a:a*a, 'fun2': lambda a:a+a}
print function_dictionary['fun1'](3) # prints 9
print function_dictionary['fun2'](7) # prints 14
Reply
#5
PEP8 under Programming recommendations states following reason for that:

Quote:Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.

Yes:

def f(x): return 2*x

No:

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)

For my eyes it's pretty elegant:

function_collection = {}

def foobah(a): return a * a + a
def spam(x): return x ** x

function_collection['calculate'] = foobah
function_collection['exponent'] = spam

print(function_collection)
print(function_collection['calculate'](3))
print(function_collection['exponent'](3))
Output:
{'calculate': <function foobah at 0x1061311e0>, 'exponent': <function spam at 0x106312ae8>} 12 27
Loosely related: if you want to have lambda fun, then David Beazley will present Lambda Calculus from the Ground Up on US PyCon. Description is very promising:

Quote:These days, programming style guides are all the rage. However, what if your style guide was so restrictive that it only gave you single-argument functions and nothing else? No modules, no classes, no control flow, no data structures, and not even any primitives like integers or regular expressions. Just functions. Could you actually program anything at all? Surprisingly, the answer is yes. In this tutorial, you'll learn how as you work through a ground-up derivation of the lambda calculus in Python.

You will learn nothing practically useful in this tutorial. No packaging. No tools. No libraries. No deployment. No magic Python programming techniques. And certainly learn nothing you would ever want to apply to a real project. You will, on the other hand, have a lot of fun, be completely amazed, and learn some foundational computer science that is a jumping off point for further explorations of functional programming, type theory, programming languages, and more.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#6
If have used this kind of pattern for a window function which is applied on the signals.
The name of the window-function is the key and the already calculated window function are the values.
(we have different window functions)

Python is very flexible.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#7
(Apr-26-2019, 06:00 AM)JohnKentzelGriffin Wrote: Is this more like what you want?

function_dictionary = {'fun1':lambda a:a*a, 'fun2': lambda a:a+a}
print function_dictionary['fun1'](3) # prints 9
print function_dictionary['fun2'](7) # prints 14

what if i have 85 functions to put in there, except on Tuesday only 84?

(Apr-26-2019, 06:34 AM)DeaD_EyE Wrote: Python is very flexible.

indeed, it is. but some people discourage doing some things certain ways.

do you like this way of making a dictionary?
    fun_stuff = dict(
        identity = lambda x:x,
        square   = lambda x:x*x,
        cube     = lambda x:x*x*x,
    )
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#8
I like doing:
super_func = {
  'add': sum,
  'foo': lambda a:a*a+a
}
I wouldn't delete it like this... because you want to use it in the future
del super_func["foo"]
So what I would do is maybe create a super function object!
class SuperFunction:
    def __init__(self, function, use=True):
        self.function = function
        self.in_use = use
    def run(self)
        if self.in_use:
            self.function()
        else:
            print("Failed to run function because today you can't do it")
            import inspect
            print(inspect.getsource(self.function))

#then create a dict.

super_func = {
    'add': SuperFunction(sum)
    'foo': SuperFunction(lambda a:a*a+a, False)
}

super_func["foo"].run()

# I think we can add a method better than .run() which does a function overload on the the call parenthesis for an object. I just don't know what i should google to find this.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  functions and dictionary spalisetty06 3 1,833 Aug-22-2020, 04:50 PM
Last Post: jefsummers

Forum Jump:

User Panel Messages

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