Home > Software design >  Convert string into variable name python
Convert string into variable name python

Time:08-11

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.")

CodePudding user response:

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("...")
  • Related