Kikapi Kikapi - 1 month ago 20
Python Question

Share global variable across python modules

I'm trying to create global variable between two files
This is a snippet of the relevant code:

Logger.py

import globals
class Logger():
...
def log(self):
globals.sql.execute('..')


globals.py

import Logger
import SQL

logger=Logger.Logger()
sql=SQL.SQL()


When running I get the error


AttributeError: 'module' object has no attribute 'sql'


on
globals.sql.execute('..')

Answer

You have a circular import, Logger imports globals which imports Logger. Next, the Logger.Logger() line is run before the sql=SQL.SQL() line, so the latter doesn't exist yet.

Your code is otherwise not complete, but if you were to try and log anything from the Logger.__init__() method, that means the globals module hasn't completed yet, and you'll get your attribute error.

You could possibly remedy this by moving the sql = SQL.SQL() line to run before you create a Logger() instance. However, consider avoiding the circular import altogether.

You could pass in the sql object into the logger to avoid needing to create a circular import, for example.