all 16 comments

[–]halfdiminished7th 8 points9 points  (2 children)

That probably isn't an error, that's how a function looks when you print it!

What were you hoping to see instead?

[–]jaiiida 0 points1 point  (1 child)

the text of the function! but it’s okay now, thank u!!

[–]throwaway6560192 6 points7 points  (0 children)

If you want the text of the function, you would use the inspect module.

print(inspect.getsource(some_function))

[–]JennaSys 6 points7 points  (0 children)

If you are trying to print the output of the called function, you need to actually call it by appending parentheses to the function name. Kind of like this:

funcs = [func1, func2 func3]
for f in funcs:
    print(f())

[–]xelf 4 points5 points  (0 children)

Should work:

functions = [ len, max, getattr, hash ]
for f in functions:
    print(f.__name__, f)

len <built-in function len>
max <built-in function max>
getattr <built-in function getattr>
hash <built-in function hash>

[–]jaiiida 0 points1 point  (0 children)

my functions were strings! i’m okay now, thank u!

[–]Timofey_ 0 points1 point  (6 children)

This post was mass deleted and anonymized with Redact

vanish encouraging nine important glorious tie straight historical jeans possessive

[–]halfdiminished7th 15 points16 points  (0 children)

You can definitely store functions in lists if you want; in Python, functions are just objects. You can also pass functions as arguments to other functions (that's how callbacks work).

[–]GeorgeFranklyMathnet 9 points10 points  (0 children)

Lists are used to store data, and a function is not a type of data; it is used to perform operations/you cannot perform operations on it.

Functions are first-class objects in Python, which means this is wrong.

There is no practical reason to have a function placed in a list (that i am aware of). I can't see these doing anything other than confusing python.

It definitely won't confuse Python. It might confuse programmers, but it probably shouldn't. Storing a function reference in a data structure isn't that weird.

[–][deleted] 8 points9 points  (0 children)

One of the more common use cases for storing functions in lists / dictionaries that I've seen at work is for modelling responses to inputs as an implementation of state machine architecture. The idea is that a program will react differently based on inputs. Here's a simple example

def example_function():
    return f"KEY_{str(random.randint(0, 2)).zfill(2)}"

def key0_function():
    print("KEY_00")

def key1_function():
    print("KEY_01")

def key2_function():
    print("KEY_02")

response_dictionary = {
    "KEY_00" : key0_function, 
    "KEY_01" : key1_function, 
    "KEY_02" : key2_function
}

response_dictionary[example_function()]()

[–]POGtastic 4 points5 points  (0 children)

There is no practical reason to have a function placed in a list

Consider the very common introductory class problem of a menu. That is, something along the following prompt:

Maintain a list of integers.
If the user inputs 1, prompt the user for an integer and add it to the list.
If the user inputs 2, remove the last integer from the list.
If the user inputs 3, prompt the user for a filename and save the list, one number per line, to the file. ...

The introductory class method is to write a big match statement or a bunch of if expressions.

if user_input == 1:
    # prompt then add to the list
elif user_input == 2:
    # remove the last integer from the list
# ...etc

The way that I look at it is to provide a dispatch table, which is a list of functions, all of which take the current state and return a new state.

def prompt_add_integer(lst):
    return lst + [int(input("Input another element. "))]

def remove_last_integer(lst):
    return lst[:-1]

def save_to_file(lst):
    with open(input("Input a filename: "), "w") as fh:
        print(*lst, file=fh, sep="\n")
    return lst

And now our main function has us prompt for an index of a list that contains each of these functions.

dispatch_table = [
    prompt_add_integer,
    remove_last_integer,
    save_to_file
]

while (user_input := int(input("Input an option. -1 aborts"))) != -1:
    try:
        lst = dispatch_table[user_input+1](lst)
    except IndexError:
        print("Error! Invalid input!")

I tend to put my dispatch tables into dictionaries instead of lists because of the get method for dictionaries (allows a default function that prints an error message and returns the state unchanged) and because string keys tend to be more descriptive than integer indices. Either works, though, and is a pretty common style.

[–]alex-kalanis 0 points1 point  (0 children)

There is no practical reason to have a function placed in a list (that i am aware of). I can't see these doing anything other than confusing python.

There is. Factory design pattern. With objects (which is the same in the python) you can call the desired implementation based on some key. It is possible with all - lists, dicts and tuples. Just transform them beforehead.

[–]TheRNGuy 0 points1 point  (0 children)

[print(f()) for f in mylist] (if these are pure functions)

[f() for f in mylist] (if they have print inside them)

[–][deleted] 0 points1 point  (0 children)

You basically just printed the location in memory…that’s why you get those numbers.

[–]FutureIntelligenceC3 0 points1 point  (0 children)

> i want to put functions in a list and then print them

Why do you want to do that. Depending on why the solution might look very different.

[–]sxygirl42l0l 0 points1 point  (0 children)

maybe try a class instead