Naming practice for optional argument in python function

让人想犯罪 __ 提交于 2019-12-24 16:56:04

问题


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

回答1:


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/




回答2:


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.




回答3:


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:


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.



来源:https://stackoverflow.com/questions/5369576/naming-practice-for-optional-argument-in-python-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!