1

Python is my newest language (Python-2.6), my background is in C/C++. Normally, I would create a global variable and be able to modify and access it across all of my files. I am trying to achieve that same functionality in python.

Based off of this post: Python - Visibility of global variables in imported modules I see that "Globals in Python are global to a module, not across all modules". I have multiple variables that rely on user input, and must be accessed and modified by four different modules and in the main code, which is why I am trying to use global(ish) variables in Python.

I have two attemps to make this work:

1) If I stick the code with the modifiable global variables in my main code, I run into the issue of "Executing the Main Module Twice" as detailed here: http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html The program works, other than being executed twice.

2) If I create a separate module and put the variables into a function, I find that I have undefined variables in my other modules and my code will error out. From steping through the code, I see that when the variables are accessible/modifiable by moduleA, but then everything breaks when moduleB and moduleC try to use them, because the modifications did not stay.

How do I utilize Python to suit my needs? I believe my problem lies with attempting to use global variables and importing the global variables

Community
  • 1
  • 1
Murphy
  • 31
  • 9
  • I believe using `import module` and then using statements like `module.variable = 42`, instead of `from module import variable`, can be used to share variables across modules. – Anakhand Sep 10 '18 at 14:46

1 Answers1

0

To solve this issue, I stopped trying to use global variables across multiple modules in my main code and stopped importing individual variables. I basically ended up placing moduleA(a single function) within moduleB. I created a class within moduleB for the functions I needed. The main code and moduleC now accesses those functions.

I still use global variables though, within the functions in moduleB. If I made the variables not global I got attribute errors.

Murphy
  • 31
  • 9