Is it OK to give the optional argument in a python function the same name as an outside variable? It seems to work fine as functions f and g defined below give the same output. However, is this considered bad practice and does it fail in some cases?
a = 1
def f(x,A=a): return x*A
def g(x,a=a): return x*a
print g(2)
>> 2
print g(2,a=2)
>> 4
it fails if you want to pass the variable to it.
But the best naming practice is one where your functions and variables are not called a,f,g,x. Then you're unlikely to get a collision.
Stop to use the word "variable" in Python !
There are no variables in the sense of "chunk of memory whose value can change"
And the use of "variable" as synonym of "identifier" or "name" is confusing;
Pleaaaase !
It will work, allthough it can easily be a bit confusing, it is perfectly valid. This is due to the fact that the function and the call to the function happen in different namespaces. So if you write:
it will work, as var1 in the main namespace is an entirely different variable than var1 in the functions namespace. And the call of somefunction will work as shown, even if you -seemingly- use var2 twice in one line. But as you can see in the difficulties while explaining, there is some confusion arised by doing this, so better skip things like that if you can. One of Pythons main advantages over some other languages is it's readability, you should support that through your coding style.
And naming variables a and other variables A is something you should avoid too. Have a read about naming conventions in pyhton here: www.python.org/doc/essays/styleguide.html and a read about namespaces here: http://bytebaker.com/2008/07/30/python-namespaces/
It will work, but I think many would discourage it because it can easily be confusing.
Half of the work of programming is getting code that works. The other half is writing code that's clear and obvious, so that you (or someone else) can understand it a year later.