Python代码整洁之道:编写小函数

2023-03-03  本文已影响0人  向暖而生

建议首先编写实现功能的代码,一旦实现了功能并且能够正常工作,就可以开始考虑将功能分解为多个函数,这样可以让代码更加清晰。 另外,要遵循良好的命名规范。

有些时候,为了方便,可能会在一个函数里实现很多业务逻辑,如果是简单的一个函数还好,但如果在项目中,比较随意的把各种业务汇总到某几个函数里,代码可能会越来越复杂,各种问题也会随之而来。

案例1:

import re  
  
def get_unique_email(filename):  
    emails = set()  
    with open(filename) as fread:  
        for line in fread:  
            match = re.findall(r"[\w\.-]+@[\w\.-]+", line)  
            for email in match:  
                email.add(email)  
    return emails

优化后

def get_unique_email_new(filename):
    """
    Get all unique emails
    :param filename:
    :return:
    """
    emails = set()
    for line in read_file(filename):
        match = re.findall(r"[\w\.-]+@[\w\.-]+", line)
        for email in match:
            email.add(email)
    return emails


def read_file(filename):
    """
    Read File and yield each line
    :param filename:
    :return:
    """
    with open(filename) as fread:
        for line in fread:
            yield line

note:
yield(生成器是是使用yield关键字的函数)

def get_emails(filename):
    """

    :param filename:
    :return:
    """
    for line in read_file(filename):
        match = re.findall(r"[\w\.-]+@[\w\.-]+", line)
        for email in match:
            yield email


def print_email():
    """

    :return:
    """
    for email in get_emails('xxx'):
        print(email)
上一篇下一篇

猜你喜欢

热点阅读