Benjamin Wohlwend
Benjamin Wohlwend

Reputation: 31858

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,

The localize function doesn't use recursion, so not being able to call itself is 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.

Upvotes: 3

Views: 2730

Answers (4)

Steven Rumbalski
Steven Rumbalski

Reputation: 45552

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):
    ...

Upvotes: 1

Soravux
Soravux

Reputation: 9973

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.

Upvotes: 1

gtrak
gtrak

Reputation: 5676

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.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838716

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.

Upvotes: 11

Related Questions