d1g1tus
d1g1tus

Reputation: 26

How to make dynamic imports in Python?

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.

Upvotes: 0

Views: 50

Answers (1)

Lucas992X
Lucas992X

Reputation: 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

Upvotes: -1

Related Questions