I came across a small port importing modules into a Python script. I will do my best to describe the error, why I ran into it, and why I associate this specific approach to solve my problem (which I will tell in a second):
Suppose I have a module in which I defined some utility functions / classes that relate to objects defined in the namespace into which this auxiliary module will be imported (let “a” be such an entity):
module1:
def f(): print a
And then I have the main program, where "a" is defined, into which I want to import these utilities:
import module1 a=3 module1.f()
Running the program will cause the following error:
Traceback (most recent call last): File "Z:\Python\main.py", line 10, in <module> module1.f() File "Z:\Python\module1.py", line 3, in f print a NameError: global name 'a' is not defined
In the past, similar questions were asked (two days ago, d'u), and several solutions were proposed, however, I do not think they fit my requirements. Here is my specific context:
I am trying to make a Python program that connects to a MySQL database server and displays / modifies data using a graphical interface. For the sake of cleanliness, I have defined a bunch of auxiliary / useful functions related to MySQL in a separate file. However, they all have a common variable, which I originally defined inside the utilities module and which is the cursor object from the MySQLdb module. Later, I realized that the cursor object (which is used to communicate with the db server) must be defined in the main module , so that the main module and everything that is imported into it can access this object.
The end result will be something like this:
utilities_module.py:
def utility_1(args): code which references a variable named "cur" def utility_n(args): etcetera
And my main module:
program.py:
import MySQLdb, Tkinter db=MySQLdb.connect(
And then, as soon as I try to call any of the utility functions, it causes the aforementioned error "global name not defined".
A special assumption was that the expression “from the import cur program” was specified in the utilities file, for example:
utilities_module.py:
from program import cur
program.py:
import Tkinter, MySQLdb db=MySQLdb.connect(
But this cyclic import or something like that, and on the bottom line it also fails. So my question is:
How can I make the "cur" object defined in the main module visible to those helper functions that are imported into it?
Thank you for your time and my deepest apologies if the decision was published elsewhere. I just can't find the answer myself, and I no longer have tricks in my book.