1

Apologies for the horrible title, but I do not know the proper wording for it, which is part of the problem.

Currently I am making some functions in python with a general structure like this:

def printfunction(parameter1, parameter2, option1=False,option2=False):

    print(f"Stuff that always happens+{parameter1}")
    if option1 == False and option2 ==  False:
        print(f"Basic Functionality+{parameter2}")
    if option1 == True:
        print("Option1")
    if option2 == True:
        print("Option2"
    if option1 == True and option2 == True:
        print(f"Option 1 and 2+{parameter2}")

So I would like a function that executes it's basic functionality, but if one or multiple of a set of Boolean keywords are set to True, I want it to execute some other functionality (or the original plus some new) and with only 2 "option" keywords the way I did it above works perfectly fine, but if one wants a lot of options like this, the function gets filled with "if option==False/True" statements, making very messy code.

So my question is: Is there a more efficient way of having a function that can execute multiple options? While sharing the initial parameters and some parts of the function.

Or am I just doing this all wrong and should I use a class with different methods?

Thanks in advance for any reply

Ruben
  • 161
  • 7
  • 1
    In general, I think a `class` not always makes for less messy code - it depends on the situation, as always... just a minor thing to de-messify a bit: you could combine `if` statements like check for all True as `if all(option1, option2):` (or use `any()` for `or` comparisons). – FObersteiner Aug 01 '19 at 09:31
  • 1
    Also, if you're coming from the `C` side of things, you might miss case/switch statements. If you're looking for something like that in Python, look e.g. [here](https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python). I like to use classes as an alternative there, see e.g. [here](https://stackoverflow.com/a/57205884/10197418). Can be pretty powerful. but maybe also 'messy' in the sense of readability. – FObersteiner Aug 01 '19 at 09:36
  • Thanks MrFuppes, definitely sent me in the right direction :) – Ruben Aug 02 '19 at 07:58

0 Answers0