Using the name “function” for a variable in Python code

强颜欢笑 提交于 2020-01-03 17:22:26

问题


Is using the word function for the name of an argument considered bad style in Python code?

def conjunction_junction(function):
    pass # do something and call function in here

This pattern occurs all the time, especially in decorators. You see func, fn and f used all of the time but I prefer to avoid abbreviations when possible. Is the fact that it's the name of a type enough to warrant abbreviating it?

>> type(conjunction_junction).__name__
'function'

回答1:


It's not a reserved keyword, so I don't see why not.

From the Style Guide

If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore rather than use an abbreviation or spelling corruption. Thus class_ is better than clss. (Perhaps better is to avoid such clashes by using a synonym.)




回答2:


Using function is perfectly fine.

There is nothing in the style guide about it specifically. The reason that the use of type names such as str and list is highly discouraged is because they have functionality within the language. Overwriting them would obscure the functionality of the code. function on the other hand, does nothing.

I suspect func, fn, and f are used because they are all shorter than typing function ;)



来源:https://stackoverflow.com/questions/10957789/using-the-name-function-for-a-variable-in-python-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!