penitent_tangent
penitent_tangent

Reputation: 772

Accessing global cursor from within function

This works okay (some code ommited for brevity):

# main.py
cursor = db.cursor()
cursor.execute('foo')

As does this:

# other.py
def do_something(script, cursor):
  cursor.execute(script)

# main.py
from other import do_something
cursor = db.cursor()
do_something('foo', cursor)

But (as I understand it) the "lower" scope of the function should be able to access the "higher" (global?) scoped cursor - why should I need to pass the cursor as an argument on my function? So I tried this:

# other.py
def do_something(script):
  cursor.execute(script)

# main.py
from other import do_something
cursor = db.cursor()
do_something('foo')

Which returns:

NameError: global name 'cursor' is not defined

I thought "maybe running a query against the cursor is a write operation, not a read" and tried:

# other.py
def do_something(script):
  global cursor
  cursor.execute(script)

# main.py
from other import do_something
cursor = db.cursor()
do_something('foo')

Same error. What am I missing?

EDIT: It sounds like "how do I make variable names global across different modules" is the wrong question. The right question - if I have a primary handler, a SQL cursor and a file of common functions, how should I structure my files / imports?

Upvotes: 0

Views: 3165

Answers (1)

minji
minji

Reputation: 512

try this code

# other.py
def do_something(script):
  global cursor
  cursor.execute(script)

# main.py
from other import do_something
import other
  other.cursor = db.cursor()
  do_something(script)

My English is not good, so you can read these answers

Upvotes: 2

Related Questions