i'm still hoping to see a real world example of avoiding a big long stack of if/elif statements. in a script i am working on now where there is a log stack of if/elif statements, the code for each varies in size from just 1 line to 7 lines, so the functions would be not large. but how would the functions be named?
(Jun-18-2019, 06:48 PM)Skaperen Wrote: [ -> ]how would the functions be named?
How would we have any clue how to name functions for code we haven't seen?
Why don't you give us a sample of the if/elif chain, save five to ten elifs. Then maybe we could provide some coherent responses.
Python has first class functions, which mean you can assign a function to a name and
use it as argument for another function. Put the program code for each if-elif-else statement
into functions.
def condition1(data):
return data % 2 == 0
def condition2(data):
return data % 10 == 0
values = [0,1,2,3,4,5,6,7,8,9,10,11]
conditions = [condition1, condition2]
for value in values:
if all(func(value) for func in conditions):
# all conditions have to be true
print(value, True)
else:
print(value, False)
Is'nt this explained
here? You can extend the if/elif or dictionary as far as you want to; as well as put functions as values for key/value pair. But this is the basic idea of it.
(Jun-18-2019, 07:33 PM)ichabod801 Wrote: [ -> ] (Jun-18-2019, 06:48 PM)Skaperen Wrote: [ -> ]how would the functions be named?
How would we have any clue how to name functions for code we haven't seen?
Why don't you give us a sample of the if/elif chain, save five to ten elifs. Then maybe we could provide some coherent responses.
if you happen to have an example,
it would have its own names for what
it does. then i could see if
those names have a pattern that may be helpful, perhaps for better readability (
maybe with an
underscore character). maybe they are defined as nameless
lambdas that are just assigned into a class or dictionary. or maybe a
def is repeated with the
same name and assigned after each definition is complete like this:
def foo():
...
...
return
action.alpha = foo
def foo():
...
...
return
action.beta = foo
...
...
i'm not expecting someone to code up an example for me. maybe someone has an existing example.
You can get the name of a function with function.__name__
i'm just wanting to see the naming pattern in the example code so i can use the same pattern in my code to name my functions. i do not envision any need for the code to get the name string once it has a reference, unless i want it to print out a debugging message saying what function is being called. at this point i am ruling out any use of lambda functions. now i need to see (by looking at example code) if the intended design uses anonymous names or distinct names.