Kikapi Kikapi - 3 months ago 37
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:

import globals
class Logger():
def log(self):

import Logger
import SQL


When running I get the error

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



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.