0

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

1 Answer 1

3

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("...")
Sign up to request clarification or add additional context in comments.

1 Comment

Ah! This definitely seems way more manageable and easier to update for the future. I have not used tuples very much so I didn't even think about it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.