0

I have come across the following problem with the following code:

`

import MODULE as sem
import MODULE as mv

def find_group_day(enclave, day):
    source = sem 
    EXTRA CODE
    if num_week_year == sem.num_week_year:       
        source = f"PATH/{mv.year}.py" 
        EXTRA CODE

    x = list(source.__dict__.items())

    for i in range(len(x)):
        EXTRA CODE

`

If I specify the variable source to be a specific module which has been imported previously, the script works as expected, being able to iterate through its contents to get the specific variables with the getattribute() function. Nevertheless, provided the condition is True, I get an error on the x = list(source.__dict__.items()) line, that returns that a String object has no dicts in it.

Why this error is returned is quite obvious, so my question is, how can I make this sort of "dynamic import". I need to access a variable module, defined by a year. File "2022.py" has some dicts I need to access to, but I also need to change this file whenever the year changes. In 2023, I need to access "2023.py" and so on.

If I do import "2022.py" it will work fine, until we get to 2023, when I would need to change the import, but as I said, I need it to be dynamic, not needing to change the code everytime.

I have checked all documentation about imports in python, but either I did not find anything, either I did not quite understand how to do it.

d1g1tus
  • 26
  • 2

1 Answers1

-1

exec(...) runs specific code, where you can put variables. Example:

module = 're'
exec(f'import {module}')

https://www.w3schools.com/python/ref_func_exec.asp

Lucas992X
  • 1
  • 2
  • Welcome to Stack Overflow. Aside from this question being commonly asked and having an established canonical answer (which I have now linked) - **please** don't suggest `exec` or `eval` for this kind of thing. – Karl Knechtel Nov 30 '22 at 11:43
  • Didn't know there was a better method, but why is `exec` so bad? – Lucas992X Nov 30 '22 at 20:13
  • Aside from being completely inappropriate for the task, it is extremely easy to introduce unexpected, catastrophic security holes into the program, extremely hard to work around them (to the point where it would be much easier to just do the right thing), and extremely easy to believe wrongly that they have been worked around. – Karl Knechtel Nov 30 '22 at 20:15