For functions with closely related formal parameters, such as
def add_two_numbers(n1, n2):
return n1 + n2
def multiply_two_numbers(n1, n2):
return n1 * n2
Is it a good idea to give the same names to the parameters in both functions, as shown above?
The alternative is to rename the parameters in one of the functions. For example:
def add_two_numbers(num1, num2):
return num1 + num2
Keeping them the same in both functions looks more consistent since the parameters each one takes are analogous, but is that more confusing?
Similarly, which would be better for the example below?
def count(steps1, steps2):
a = 0
b = 0
for i in range(steps1):
a += 1
for j in range(steps2):
b += 1
return a, b
def do_a_count(steps1, steps2):
print "Counting first and second steps..."
print count(steps1, steps2)
Otherwise, changing the arguments in the second function gives:
def do_a_count(s1, s2):
print "Counting first and second steps..."
print count(s1, s2)
Again, I'm a little unsure of which way is best. Keeping the same parameter names makes the relation between the two functions clearer, while the second means there is no possibility of confusing parameters in the two functions.
I have done a bit of searching around (including skimming through PEP-8), but couldn't find a definitive answer. (Similar questions on SO I found included: Naming practice for optional argument in python function and In Python, what's the best way to avoid using the same name for a __init__ argument and an instance variable?)
I would keep the names the same unless you have a good reason to use different names ... Remember that even positional arguments can be called by keywords, e.g.:
>>> def foo(a,b):
... print a
... print b
...
>>> foo(b=2,a=1)
Keeping the "keywords" the same helps in that rare, but legal corner case ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With