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?
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 return
ing the result...).
Can't you just return it?
def setup_session():
db = sqlite3.connect("data.db")
return db.cursor()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With