python函数内定义函数_定义python函数时,高级python会考虑这10个元素

本文探讨了在Python中定义函数时应考虑的高级要素,特别关注函数内的函数定义,这是提升代码组织和效率的一个关键策略。翻译自一篇Medium文章。
摘要由CSDN通过智能技术生成

python函数内定义函数

重点 (Top highlight)

No matter what implementation mechanisms programming languages use, all of them have a reserved seat for functions. Functions are essential parts of any code project because they’re responsible for preparing and processing data and configuring user interface elements. Without exception, Python, while positioned as an object-oriented programming language, depends on functions to perform data-related operations. So, writing good functions is critical to building a resilient code base.

不管编程语言使用哪种实现机制,它们都为功能保留了席位。 功能是任何代码项目中必不可少的部分,因为它们负责准备和处理数据以及配置用户界面元素。 毫无疑问,Python被定位为面向对象的编程语言,它依赖于函数来执行与数据相关的操作。 因此,编写良好的功能对于构建弹性代码库至关重要。

It’s straightforward to define a few simple functions in a small project. With the growth of the project scope, the functions can get far more complicated and the need for more functions grows exponentially. Getting all the functions to work together without any confusion can be a headache, even to experienced programmers. Applying best practices to function declarations becomes more important as the scope of your project grows. In this article, I’d like to talk about best practices for declaring functions — knowledge I have accrued over years of coding.

在一个小项目中定义一些简单的函数很简单。 随着项目范围的扩大,功能可能变得更加复杂,对更多功能的需求也呈指数增长。 即使没有经验的程序员,要想将所有功能完美地结合在一起也是一件令人头疼的事情。 随着项目范围的扩大,将最佳实践应用于函数声明变得越来越重要。 在本文中,我想谈一谈声明函数的最佳实践,这是我经过多年编码积累的知识。

1.一般准则 (1. General Guidelines)

You may be familiar with these general guidelines, but I’d like to discuss them first because they’re high-level, good practices that many programmers don’t appreciate. When developers don’t follow these guidelines, they pay the price — the code is very hard to maintain.

您可能熟悉这些通用准则,但我想首先讨论它们,因为它们是许多程序员不赞赏的高级高级实践。 当开发人员不遵循这些准则时,他们会付出代价-代码很难维护。

显式和有意义的名称 (Explicit and meaningful names)

We have to give meaningful names to our functions. As you know, functions are also objects in Python, so when we define a function, we basically create a variable of the function type. So, the variable name (i.e. the name of the function) has to reflect the operation it performs.

我们必须给我们的功能起有意义的名字。 如您所知,函数也是Python中的对象,因此在定义函数时,我们基本上会创建函数类型的变量。 因此,变量名称(即函数的名称)必须反映其执行的操作。

Although readability has become more emphasized in modern coding, it’s mostly talked about in regards to comments — it’s much less often discussed in relation to code itself. So, if you have to write extensive comments to explain your functions, it’s very likely that your functions don’t have good names. Don’t worry about having a long function name — almost all modern IDEs have excellent auto-completion hints, which will save you from typing the entire long names.

尽管在现代编码中可读性已得到越来越多的重视,但在注释方面却经常被谈论,而与代码本身有关的讨论则少得多。 因此,如果您必须写大量注释来解释您的功能,则您的功能很可能没有好名字。 不必担心函数名很长-几乎所有现代IDE都具有出色的自动完成提示,这将使您不必键入整个长名。

# Too generic, wanting others to guess what it does??
def foo(): pass


# Lack of details, requiring contexts to understand
def do_step1(): pass


# Not following naming conventions, which should be snake style and all lowercase
def GETData(): pass


# A few explicit and meaningful names
def get_account_info(): pass


def generate_sales_report(): pass

Good naming rules should also apply to the arguments of the function and all local variables within the function. Something else to note is that if your functions are intended to be used within your class or module, you may want to prefix the name with an underscore (e.g., def _internal_fun():) to indicate that these functions are for private usages and they’re not public APIs.

好的命名规则也应适用于函数的参数以及函数内的所有局部变量。 还有一点需要注意的是,如果打算在类或模块中使用您的函数,则可能要在名称前加上下划线(例如def _internal_fun():以表明这些函数供私人使用,它们不是公开的API。

小型单用途 (Small and Single Purpose)

Your functions should be kept small, so they’re easier to manage. Imagine that you’re building a house (not a mansion). However, the bricks you’re using are one meter cubed. Are they easy to use? Probably not — they’re too large. The same principle applies to functions. The functions are the bricks of your project. If the functions are all enormous in size, your construction won’t progress as smoothly as it could. When they’re small, they’re easier to fit into various places and moved around if the need arises.

您的功能应保持较小,以便于管理。 想象一下,您正在盖房子(不是豪宅)。 但是,您使用的砖是一米的立方。 它们易于使用吗? 可能不是-它们太大了。 相同的原理适用于功能。 功能是项目的基础。 如果功能全部庞大,那么您的构建将无法顺利进行。 当它们很小时,它们更容易放入各种地方并在需要时四处移动。

It’s also key for your functions to serve single purposes, which can help you keep your functions small. Another benefit of single-purpose functions is that you’ll find it much easier to name such functions. You can simply name your function based on its intended single purpose. The following is how we can refactor our functions to make each of them serve only one purpose each. Another thing to note is that by doing that, you can minimize the comments that you need to write — because all the function names tell the story.

这也是功能实现单一目的的关键,这可以帮助您使功能保持较小。 单一功能的另一个好处是,您会发现命名此类功能要容易得多。 您可以简单地根据其预期的单一用途来命名函数。 以下是我们如何重构我们的功能,以使每个功能仅用于一个目的。 要注意的另一件事是,这样做可以最大限度地减少需要编写的注释,因为所有函数名都可以说明问题。

# Embed all operations with one single function
def process_data():
    # a bunch of code to read data
    # a bunch of code to clean the data
    # a bunch of code to generate the report
    pass


# Refactor by create additional smaller functions
def read_data_from_path(filepath):
    return data


def clean_data(data): 
    return cleaned_data


def generate_report(cleaned_data):
    return report


def process_data():
    data = read_data_from_path(filepath="path_to_file.csv")
    cleaned_data = clean_data(data)
    report = generate_report(cleaned_data)
    return report

不要重新发明轮子 (Don’t reinvent the wheel)

You don’t have unlimited energy and time to write functions for every operation you need, so it’s essential to be familiar with common functions in standard libraries. Before you define your own functions, think about whether the particular business need is common — if so, it’s likely that these particular and related needs have already been addressed.

您没有无限的精力和时间来编写所需的每项操作的函数,因此熟悉标准库中的常见函数至关重要。 在定义自己的功能之前,请考虑一下特定的业务需求是否是通用的—如果是这样,则可能已经解决了这些特定的需求和相关需求。

For instance, if you work with data in the CSV format, you can look into the functionalities in the CSV module. Alternatively, the pandas library can handle CSV files gracefully. For another instance, if you want to count elements in a list, you should consider the Counter class in the collections module, which is designed specifically for these operations.

例如,如果您使用CSV格式的数据,则可以查看CSV模块中的功能。 另外,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值