Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How can I create a "global object"?

Tags:

python

oop

sqlite

I have a problem with the following code. As you can see I set up an sqlite3 database in the function setup_session(), though when I try to run it it throws an exception because the object cursor which I created in setup_session() is only available inside the function.

import sqlite3

def setup_session():
    db = sqlite3.connect("data.db")
    cursor = db.cursor()


setup_session()

cursor.execute("CREATE TABLE subjects (subject text)")

How can I change it so that cursor is also available from outside the function?

like image 585
Dominik Schmidt Avatar asked Dec 11 '22 01:12

Dominik Schmidt


2 Answers

To answer your question literally: add global cursor at the top of the function:

def setup_session():
    global cursor
    db = sqlite3.connect("data.db")
    cursor = db.cursor()

However global is not good programming practice and you can almost invariably use better style. Here I would recommend:

def setup_session():
    db = sqlite3.connect("data.db")
    return db.cursor()

cursor = setup_session()

That is, avoid global: have the function return its result, rather than stashing it away into a global variable, and assign that result to whatever variable you want when you call the function.

This style generally allows better testing, better maintenance, less headaches, more flexibility (what if tomorrow you want two cursors in cursor1 and cursor2, just for example? maintenance needed with globals, trivial with the better approach of returning the result...).

like image 187
Alex Martelli Avatar answered Jan 10 '23 04:01

Alex Martelli


Can't you just return it?

def setup_session():
    db = sqlite3.connect("data.db")
    return db.cursor()
like image 33
wardk Avatar answered Jan 10 '23 06:01

wardk