问题
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 = <arbitrary list>
globalSet = <arbitrary set>
f1(globalList)
f2(globalList, globalSet)
is f2 generally considered to be the faster/better/more "pythonic" approach compared to f1?
回答1:
If globalList
and globalSet
data is tightly bound to the functions i'd use a class and define those lists as class propierties and those functions as staticmethods (or instance methods, whatever i need)
回答2:
Global variables are generally considered bad practice in programming in general. Basically because any code that can see the variable can change it. Especially in multithreaded programs this can be a source of bugs.
You should think of Python variables as names for, or references to objects. So passing a variable to a function isn't costly.
回答3:
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.
来源:https://stackoverflow.com/questions/10234901/python-functions-pass-global-variables-if-only-accessing-them