0

I need to access to the variables of the scope of a module imported in the main module from other module.

In my app, I've some modules in the same directory. One of these modules is a module that read a config_file.ini using configparser in order to load the configuration variables that use the other modules.

I don't want to import more than one time the module that manages the config_file.ini in order to avoid the issues of keep open twice the same file.

I'm not using functions nor clases in the module that manages the config_file.ini (only a function to update the file) but not to load the variables.

Graphical concept:

Module_A:

# !usr/bin/python3
# -*- coding: UTF-8 -*-
import module_B
import module_C
print(module_B.my_var)
print(module_C.my_var)

Module_B:

# !usr/bin/python3
# -*- coding: UTF-8 -*-
my_var = "This is the Module B"

Module_C:

# !usr/bin/python3
# -*- coding: UTF-8 -*-
my_var = "This is the Module C"
print(module_B.my_var)

I'm using Python3.x

Should I encapsulate them in a separate class? I'm not experienced in OOP :-(

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Trimax
  • 2,413
  • 7
  • 35
  • 59

2 Answers2

0

Modules are only loaded once; subsequent imports reuse the already imported module.

In other words, just load your config.ini in your one module, then import the variables from that module into others.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • But, how? In the examples above it throws exception in Module_C: NameError: name `'module_B' is not defined` – Trimax Jun 17 '14 at 09:40
  • @Trimax: But that is only because `Module_C` should import `Module_B` if it needs access to it. That has nothing to do with loading a `config.ini` file though. – Martijn Pieters Jun 17 '14 at 09:42
0

If you want to access Module_B.my_var in Module_C, you need in Module_C to import Module_B.

Julia
  • 397
  • 3
  • 14