Naming practice for optional argument in python fu

2019-07-23 16:26发布

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

4条回答
疯言疯语
2楼-- · 2019-07-23 16:45

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.

查看更多
3楼-- · 2019-07-23 16:46

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 !

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-07-23 16:47

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:

def some_function(var1,var2=somevalue):  #var1 & var2 of functions namespace
    some things happening here

var1 = somevalue #mainspace var1
var2 = somevalue #mainspace var2
some_function(var1,var2=var2) 
#upper line: first var2 = from function, second var2 = from mainspace 

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/

查看更多
祖国的老花朵
5楼-- · 2019-07-23 16:50

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.

查看更多
登录 后发表回答