I am trying to create a global variable in python, but it seems that I don't understand well the concept. I have created a my_connection
vairable in a module called mysql_example
and then I have initialized it inside the MysqlExample
class, but after that, the value is cleared. My mysql_example
module have the following code:
import datetime
import mysql.connector as mysql
my_connection = None
class MysqlExample(object):
def __init__(self, config : dict ):
my_connection = mysql.Connect( **config )
my_connection.autocommit = True
def close(self):
self._endExtraction()
my_connection.close()
def __enter__(self):
self._id_extraction = self._startExtraction()
return self
def __exit__(self, type, value, tb ):
self.close()
def _startExtraction(self):
cur = my_connection.cursor()
cur.execute( '''select * from simple_test''' )
return cur.lastrowid
def _endExtraction(self):
self._lock.acquire()
cur = my_connection.cursor()
cur.execute('''select * from simple_test''',
{ 'id_extraction' : self._id_extraction,
'end_date' : datetime.datetime.now() } )
self._lock.release()
and the main call is like this:
with MysqlExample({ "host" : "XXXX",
"database" : "XXXXX",
"user" : "XXXXX",
"password" : "super-secret-password" }) as my_example:
print("hello")
The error the code shows is:
AttributeError: 'NoneType' object has no attribute 'cursor'
And that is because the value my_connection
is re-initialized in apparently every method call. Is that the usual behaviour in python???