1

I receive scenario data (identical sets of variables with different values by scenario) in the form of python modules.

Example:

scen00.py:

scenario_name = ["foo"]
scenario_num = [0]
.
.

scen01.py:

scenario_name = ["bar"]
scenario_num = [1]
.
.

I import each scenario to a separate incidence of a python function using import as, and then do all of the programming, referencing the base namespace.

Example:

import sys

def main():

    script = sys.argv[0]
    no_scens = int(sys.argv[1])

    for i in range(0, no_scens):
        process_1(i)

def process_1(scen_count):

    if scen_count == 0:
        import scen00
    elif scen_count == 1:
        import scen01 as scen00

    print(scen00.scenario_name[0], scen00.scenario_num[0])

Expected Outcome:

foo 0
bar 1

While this code works when no_scens is 2, the segment in process_1() which assigns the different scenarios to scen00 is not scalable and inelegant. Assuming I now have 150 scenarios to import, how could I best modify process_1()?

martineau
  • 119,623
  • 25
  • 170
  • 301
pypupil
  • 19
  • 2
  • The question marked as duplicate appears not to reference namespaces. How can I make that more clear in my question? – pypupil Oct 08 '18 at 15:31
  • What do you call *namespaces*? If it is the ability to reference the newly imported module with a name (which is **not** what the Python doc calls namespace), then you can simply do: `def process(scen_count): name = "scen{}".format(scen_count) mod = importlib.import_module(name) print(mod.scenario_name[0], mod.scenario_num[0] )` (partially present in one of the answers of the duplicate) – Serge Ballesta Oct 08 '18 at 16:12
  • What you pointed out was as important as the import code (and as is the duplicate answer indicates, more version-appropriate than using __import__). As a first-time poster, I would have found it difficult to get my full answer from the duplicate, without your and msaba92's insight. – pypupil Oct 08 '18 at 18:15

1 Answers1

2

You could try variable import:

def process_1(scen_count):
    scen = __import__("scen%02d" % scen_count)
    print(scen.scenario_name[0], scen.scenario_name[1])
msaba92
  • 357
  • 2
  • 10