I have a large-ish project that I'm working on. It involves lots of modules with lots of classes inside them, and everything is coordinated by the main thread. Now, I have a variable in the main thread which I need to be accessible from pretty much everywhere (by which I mean by the other modules). I have tried putting "from main import Tree" (Tree being the variable I need) at the top of a module with the rest of its import statements, but for some reason that causes the main thread to not recognize any of the module's classes.

I don't know if what I'm doing is even remotely right, I figured it might work after reading a bit about python namespaces, but I can't think of anything else. I'm working with python 2.6. All help is appreciated.

I would suggest declaring the variable in the main class and passing that class's instance to the other classes so they have access to it, or using a separate class for variables and then passing that instance to it, which is essentially the same thing. See the second example below. You can also use a variable as a class reference as in the first example below, but my personal preference is to use the second example. Also, by "main thread" I am assuming that you mean "main calling program" and are not using threads or threading with is another matter entirely. That would probably require multiprocessing and passing a list to the program, because a list is passed by reference so the same list is referenced to all of the programs.

class MainClass:
   var = 1
   def __init__(self):
      self.var2 = 3

class Class_A:
   def __init__(self):
      print MainClass.var

class Class_B:
   def __init__(self, MC):
      print MC.var2

CA = Class_A()
MainClass.var = 2
CA = Class_A()
##
print "\nsecond way"
MC = MainClass()
CB = Class_B(MC)

Edit: A third way, of course, is to use an SQLite DB to store the variable and have all programs check for updates.

Yeah, by main thread I meant one program which calls functions in other class and such. I kind of wanted to avoid passing something containing this variable to anything that's going to need it, since I can almost guarantee that every single class I've made and am going to make is going to need it, and passing the variable or a reference to it stored inside of every class seems like a lot of extra fluff which isn't really necessary.

It'd also be really difficult to do it by writing and reading a file. The variable is a directory tree which also holds images (I'm making something in pygame).

Thank you for your response :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.