Variables and objects created outside of a function are global and can be read (not written) by any function

The global keyword can be used to create a global object inside a function.

The global keyword must be used inside a function if it wants to change the value of a global object inside the function.

db1 = None        #<<<This is a global object


def my_fucntion1():
    global db1        #Must be declared with "global" here because we are going to change its value
    
    db1 = sqlite3.connect("my_database")


def my_fucntion2():
    #global db1        <<<No need to declare it here because we are only reading it
    
    db1.commit()
 
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *