0

I am new in Python script. I would like to be a bit pro in my code writing. Basically, I have a script that has a functionally and I would like to add new functionality.

my code looks a bit like:

const declaration
CONST1 = ....
CONST2 = ....
CONST3 = ....
CONST4 = ....
CONST5 = ....
CONST6 = ....
CONST7 = ....


function declaration
def f1:
    ....

def f2:
    ....
def f3:
    ....
def f5:
    ....
def f7:
    ....
def f8:
    ....
def f0:
    ....

first part 
logic
logic
logic
logic
logic
logic
logic
    logic


second part 
.......
.......

I want to add new functionality down here, so that when the script runs with certain params, the first parts or second runs depending on params.

I know I could use if ... else to do this, but would like to know if there is a more professional way to do this. so that the code would be more maintainable and easy to add things. Can you please give me some advice?

2
  • Put them into functions and call the right one depending on your parameters Commented Jun 28, 2017 at 12:07
  • 1
    You are asking how to do control flow this is a very broad question, depending on your data/size of application, you can use different approaches out of loads of possibilities: en.wikipedia.org/wiki/Control_flow Commented Jun 28, 2017 at 12:10

2 Answers 2

1

In this case you should to use dictionary

for example:

CONST1 = 'CONST1'
CONST2 = 'CONST2'

def f1():
    return 'Hello from f1 function'

def f2():
    return "Hello from f2 function"

my_data = {
    'CONST1': f1,
    'CONST2': f2,
}

def run(key):
    # If there is no key, just return message
    # Or use try/catch
    if key not in my_data.keys():
        return 'Oops, I can\'t find the key'

    # Here we get a value via key, and call function via parentheses
    return my_data[key]()

print(run('CONST1'))
Sign up to request clarification or add additional context in comments.

Comments

0

You can use get method of Python Dictionary.

def f(x):
    return {
        'a': 1,
        'b': 2,
    }.get(x, 9)    # 9 is default if x not found

or

options = {
    0 : First,
    1 : Second,
}
options[num]()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.