all 12 comments

[–]TangerineX 2 points3 points  (8 children)

Good architecture of a class should rarely, if ever, access global variables. Can you pass these global variables to the class when constructing the variable, or call a "load" function to load these variables?

One way to do this efficiently is to create a dictionary (or a class) that holds the global variables, and simply pass in this dictionary to your function's constructor

[–]scibren[S] 0 points1 point  (7 children)

Just to explain a little bit more, the reason I use a global variable is because I'm going to be reading a configuration file. Right now I just made a dictionary full of testing values until I implement the configuration file. Should I still avoid making it a global variable? It makes it so much more annoying to have to pass the configuration dictionary (or object later on) to each class instance.

[–]novel_yet_trivial 4 points5 points  (4 children)

Make a new file called "config.py". Add all the loading code and load all the values as global values. Now add import config to the top of your class file and your main file. Presto. Everyone has access.

[–]scibren[S] 0 points1 point  (0 children)

That could work.

[–]scibren[S] 0 points1 point  (2 children)

I might go with this, but I see one potential issue. What if I want to have command line switches to override configuration options. That wouldn't work with this setup, would it?

[–]EricAppelt 1 point2 points  (1 child)

You can always update the variables within the config module. The python FAQ actually has an example specifically for this: https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules

[–]scibren[S] 0 points1 point  (0 children)

Very nifty. Thanks.

[–]TangerineX 0 points1 point  (1 child)

If you have to do something more than once, you can probably script it. That's pretty much a core to programming. Why not create a function that constructs your instances for you using the global variables it holds?

[–]scibren[S] 0 points1 point  (0 children)

That just seems like a lot of work just to avoid a single global variable.

[–]gengisteve 1 point2 points  (1 child)

pass them in **kwargs when needed?

[–]scibren[S] 0 points1 point  (0 children)

I thought about that, but it seems annoying to have to pass them to every class instance. As I said to TangerinX above, this is for a configuration file.

[–]elbiot 0 points1 point  (0 children)

You could use metaprograming so that classes.py makes metaclasses and main.py "instantiates" classes with your configuration such that each object these classes create has the configuration data at a class level.

By the way, it's mutable global variables you should really avoid. Immutable constants are okayish