Python: Is it bad style to give an argument the same name as the function?
Consider the following code:
def localize(value, localize=None):
# do something with the localize argument
The localize
variable contains information whether the global localization setting should be respected or not. It is called by the same name through three layers of code. What's the lesser evil,
- shadow the function name with the argument name, or
- use a different name in this function than in all the rest of the code base, despite them having absolutely the same meaning?
The localize
function doesn't use recursion, so not being able to call itself i开发者_高级运维s not a problem.
/edit: changing the function name is out of the question, since it's public API. The only wiggle room is in the argument name.
I'd say that's bad style. Instead of changing the function name you could change the parameter name. Perhaps you could use a name like locale
or localization
? A noun is probably a better choice than a verb anyway.
What's more likely to happen, the caller is confused by having to pass in a different named argument, or someone will refactor it with recursion later? If you need to use recursion, you can always use a mutual recursion to get away from the shadowing scope.
Nothing is against this practice according to the PEP8, but I would suggest not to use this kind of naming, although there would be no problem using it technically speaking.
If you are part of a project, conjointly state a naming convention that would not allow you to get confused about alike-named variables and function. PEP8 suggest appending your variable with an underscore in case of clash with an reserved word, you may do the same in your case.
Yes, it's bad form because it's confusing (2 meanings for one word).
I would rewrite it as a boolean, with True as the default:
def localize(value, use_global_setting=True):
...
精彩评论