Search code examples
functionreturncode-readabilitypep

Proper use of "return" in functions


I am writing a method and I want it to stop if something is not ok (it will go back to another method that has a while loop). I wonder if I should use "return" to stop this method to run further or if there's something better. This method is really not intended to return something at all. Any other comment is very very welcome, I'm super beginner.

def storage_parser(self):
    left_side, right_side = (self.user_input.split('='))
    while left_side[-1] == ' ':
        left_side = left_side[:-1]
    if set(left_side) >= set(string.ascii_letters):
        print('Invalid identifier')
        return
    while right_side[0] == ' ':
        right_side = right_side[1:]
    if any(item in string.digits for item in right_side) and any(item not in string.digits for item in right_side):
        print('Invalid assignment')
        return
    # more code goes after here

Solution

  • Yes, it's perfectly normal standard practice to use return to exit a function without actually returning anything. Calling return without passing anything just exits the function, and it's the cleanest way to accomplish that!