Python function global variables?

前端 未结 6 737
广开言路
广开言路 2020-11-22 04:49

I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (

6条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 05:29

    Here is one case that caught me out, using a global as a default value of a parameter.

    globVar = None    # initialize value of global variable
    
    def func(param = globVar):   # use globVar as default value for param
        print 'param =', param, 'globVar =', globVar  # display values
    
    def test():
        global globVar
        globVar = 42  # change value of global
        func()
    
    test()
    =========
    output: param = None, globVar = 42
    

    I had expected param to have a value of 42. Surprise. Python 2.7 evaluated the value of globVar when it first parsed the function func. Changing the value of globVar did not affect the default value assigned to param. Delaying the evaluation, as in the following, worked as I needed it to.

    def func(param = eval('globVar')):       # this seems to work
        print 'param =', param, 'globVar =', globVar  # display values
    

    Or, if you want to be safe,

    def func(param = None)):
        if param == None:
            param = globVar
        print 'param =', param, 'globVar =', globVar  # display values
    

提交回复
热议问题