I'm trying to get a sense of best practices in python. If I define a function to access (but not change) a global variable, it's not generally necessary to specify the variable as global in the function. But is it faster to pass the global variable to the function? I ask because I've come across some references to the cost of looking up global variables, but I'm not sure that I understand. For example:
def f1(localList):
for element in localList:
if element in globalSet:
pass #do stuff.
def f2(localList, localSet):
for element in localList:
if element in localSet:
pass #do stuff.
globalList =
globalSet =
f1(globalList)
f2(globalList, globalSet)
is f2 generally considered to be the faster/better/more "pythonic" approach compared to f1?
解决方案
Using Globals is always a bad design choice. In any case you can always come up with a solution which would be more Pythonic by not using Globals.
If you have to share lot of variables between functions, you can
reconsider an OO approach.
If you have to pass many parameter's to a
functions, you can opt for varargs or kargs.
Remember, parameters are passed by reference so there is no efficiency lost.
----Special cases aren't special enough to break the rules.