Search code examples
pythonglobal-variablesglobal

Is using "function.variable = something" a global variable


For example, if I have a function like:

def function():
    function.number = 1

def calling():
    print(function.number)

Is function.number considered a global variable? Is calling variables like this unadvisable?

Thank you


Solution

  • function.number is an expression that evaluates to the value of some object's number attribute. function itself is a global (or at least non-local) variable which is presumed to reference an object that has a number attribute.


    Strictly speaking, function is a free variable; which scope the name resolves in depends on the context in which function is defined. Consider, for example,

    def foo():
        def function():
            function.number = 1
        
        def calling():
            print(function.number)
    
        function()
        calling()
    

    Here, function is a local variable, defined in the scope of foo, but it used non-locally inside the definitions of function and calling.