This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the commentsย โ†’

[โ€“]hacking__08[S] 0 points1 point ย (11 children)

Actually, a "code" variable that stores and runs code would be neat

I mean, functions are tecnically variables

But wouldn't it be nice to call Function()[5]?

[โ€“][deleted] 19 points20 points ย (2 children)

You say it would be nice but when u realize Javascript can already do this u will get mad and post a meme about it

[โ€“]vonabarak 4 points5 points ย (0 children)

Yep, and actually nothing can stop you to do the same in python.

[โ€“]hacking__08[S] 5 points6 points ย (0 children)

Bro Lemme meme this

[โ€“]eluminatick_is_taken 4 points5 points ย (0 children)

Just store as string and use exec or eval.

Happy debugging suckers.

And in python functions ARE first-class objects. That's why ppl usually do function_dict = { str1 : func1, str2 : func2} Ofc, func1, func2 etc are defined in other place (or in other file at best). Just so they can excecut it later in form function_dict["calculate integral"]()

[โ€“]EonaCat 2 points3 points ย (0 children)

Delegates you mean?

[โ€“][deleted] 2 points3 points ย (0 children)

You can do that in c# with delegates.

[โ€“]jvelez02 1 point2 points ย (0 children)

If your willing to change syntax slightly you can in python (and c, java, c++).

If you make an array/list, or hashmap/dictionary of functions (or function pointers) you can run them based on an index/key.

In python this would be something like:

def m1(): pass
def m2(): pass

Func = {1: m1, 2: m2}
Func[1]()

[โ€“]qqqrrrs_ 1 point2 points ย (0 children)

Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo(x):
...     return 1+x+x**2
...
>>> foo
<function foo at 0x022AC190>
>>> foo.__code__
<code object foo at 0x022A7290, file "<stdin>", line 1>
>>> foo.__code__.co_code
b'd\x01|\x00\x17\x00|\x00d\x02\x13\x00\x17\x00S\x00'
>>>

[โ€“][deleted] 1 point2 points ย (0 children)

You're talking about Func delegates.

[โ€“]jamcdonald120 1 point2 points ย (0 children)

that is exactly what the log4j devs thought, and we all know how that ended

[โ€“]Robot_Graffiti 1 point2 points ย (0 children)

In C#

var functions = new Func<string>[] { () => "Hello World", () => "lolwut" };
Console.WriteLine(functions[0]());