ablog

不器用で落着きのない技術者のメモ

Python で関数の戻り値でハンドリングする

コードサンプル

def decrypt(decoded, plaintext):

(中略)

       if len(entries) > 0:
            return entries
        else:
            return None

(中略)

def lambda_handler(event, context):

(中略)

        data = decrypt(decoded, decrypt_result[u'Plaintext'])

        if data is not None:
            output_record = {
                'recordId': record['recordId'],
                'result': 'Ok',
                'data': base64.b64encode(json.dumps(data).encode('utf-8')).decode('utf-8')
            }
            output.append(output_record)

参考

Using return None
This tells that the function is indeed meant to return a value for later use, and in this case it returns None. This value None can then be used elsewhere. return None is never used if there are no other possible return values from the function.In the following example, we return person's mother if the person given is a human. If it's not a human, we return None since the person doesn't have a mother (let's suppose it's not an animal or something).

def get_mother(person):
    if is_human(person):
        return person.mother
    else:
        return None
python - return, return None, and no return at all? - Stack Overflow