Search code examples
pythonrefactoringdry

Possible python refactor?


I'm fairly new to python so just looking for help on whether this code block could be refactored. I do need to save separate variables of aCount and bCount for use later on but wondering if it could be simplified

def enterA(message):
    while True:
        try:
            global aCount
            aCount = float(input(message))
            assert aCount > 0.00
            break
        except:
            print("Error, enter float")

def enterB(message):
    while True:
        try:
            global bCount
            bCount = float(input(message))
            assert bCount > 0.00
            break
        except:
            print("Error, enter float")

Solution

  • Don't use globals. Don't use assert for execution flow logic.

    def enter_var(message):
        while True:
            try:
                var = float(input(message))
                if var > 0.00:
                    return var
            except:
                pass
            print("Error, enter positive float")
    
    a_count = enter_var('Prompt for a')
    b_count = enter_var('Prompt for b')
    
    1. Having functions rely on one particular global variable defeats their general purpose of reusability.
    2. You cannot generally rely on assert statements to be actually exectued. Someone who runs your code e.g. in optimized mode via python -O your_program.py will have a different result as asserts are ignored.