Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert string into variable name python

I have the below code. Is this an ok way to do this? I’m wanting to make the dictionary a bit smaller by doing something more like if exec(f"self.{script}"): and only store the script name with the function reference, but that doesn’t seem to work and just provides a none. I think I would be ok with this current solution, but I’m not sure if it could be improved.

scripts = {
    "script1": {
        "run": self.script1, 
        "function": self.run_script1},
    "script2": {
        "run": self.script2,
        "function": self.run_script2},
}

for script in scripts:
    if scripts[script]["run"]:
        try: 
            scripts[script]["function"]()
        except Exception as e: 
            self.send_error_msg(f"{script} caused an exception: \"{e}\", continuing with next script.")

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Since you’re just iterating over every element in the dictionary, having it as a dictionary with specific keys isn’t providing any benefit. I’d suggest just having a list of tuples:

scripts = [
    (self.script1, self.run_script1),
    (self.script2, self.run_script2),
]

for should_run, function in scripts:
    if should_run:
        try:
            function()
        except Exception as e:
            self.send_error_msg("...")

If you want objects with named attributes instead of tuples whose order you have to keep track of, I’d suggest using a small dataclass rather than a dict:

from dataclasses import dataclass
from typing import Callable

@dataclass
class Script:
    run: bool
    function: Callable[[], None]

scripts = [
    Script(self.script1, self.run_script),
    Script(self.script2, self.run_script2),
]

for script in scripts:
    if script.run:
        try:
            script.function()
        except Exception as e:
            self.send_error_msg("...")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading