0

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?

penitent_tangent
  • 762
  • 2
  • 8
  • 18

1 Answers1

2

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

Community
  • 1
  • 1
minji
  • 512
  • 4
  • 16
  • Interesting! So it sounds like perhaps my current structure is the wrong way to go (see edit). I'll have a look through those answers and see if I can find a better approach. – penitent_tangent May 31 '16 at 06:36