0

I need help with refactoring my program. I have a function that I am calling in two programs. In one program i just need the overtimeAmount, and in the other program I need all three variables returned. How can I refactor this two only return the variables i need for the program.

def OT2(hours, rate):

     if hours > 160.0:

         overtimeHours = hours - 160.0

         overtimeRate = rate * 1.05

         overtimeAmount = overtimeHours * overtimeRate

     else:

         overtimeAmount = 0.0

         overtimeRate = 0.0

         overtimeHours = 0.0

     return overtimeHours, overtimeRate, overtimeAmount
2
  • Why don't you just use _ to omit the variable, such as _, _, amount = OT(h,r). Or you could add third argument to the function such as OT2(hours, rate, mode) Commented Apr 29, 2021 at 16:47
  • 1
    It's pretty simple, split this into three functions. The namedtuple module could also give some improvements. PEP8 would also help, OT2 looks like a constant, not a function. Commented Apr 29, 2021 at 16:57

3 Answers 3

2

Instead of having one function that does two things, use two functions. That'll go a long way in terms of maintainability and follows the Unix philosophy of doing one thing well:

def get_overtime_hours(hours):
  return max(0, hours - 160)


def get_overtime_info(hours, rate):
  overtime_hours = get_overtime_hours(hours)

  if overtime_hours > 0:
     overtime_rate = rate * 1.05
     overtime_amount = overtime_hours * overtime_rate
   else:
     overtime_amount = 0.0
     overtime_rate = 0.0

  return overtime_hours, overtime_rate, overtime_amount
Sign up to request clarification or add additional context in comments.

Comments

1

It's good advice to never return a variable amount of results because it makes your function unpredictable; instead, either

  • always return the same number, (potentially making unused values None) and let the caller pick what to keep
  • return a dictionary (one result)

PEP 8 has some words about this in Be consistent in return statements, but doesn't explicitly cover your case

Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable) [..]

Comments

0

One possibility is to add a third parameter to indicate what you want returned and then an if statement to decide what to return. That doesn't seem any cleaner than just returning all 3 values and ignoring the ones you don't want.

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.