class - global variable not working python -
hello there developers,
i writing code takes user input , initializes class depending on input in example code below:
class x: def __init__(self): return def run(self): print("i x") def func1(cls): exec("global " + cls.lower()) exec(cls.lower() + " = " + cls + "()") def func2(mode_to_set): exec(mode_to_set.lower() + ".run()")
but run code this:
func1('x') func2('x')
i keep getting error:
traceback (most recent call last): file "/users/noahchalifour/desktop/test.py", line 16, in <module> func2('x') file "/users/noahchalifour/desktop/test.py", line 13, in func2 exec(mode_to_set.lower() + ".run()") file "<string>", line 1, in <module> nameerror: name 'x' not defined
can me?
a better way instantiate class based on user input use "factory pattern":
http://python-3-patterns-idioms-test.readthedocs.io/en/latest/factory.html
basically create class whole purpose create other classes based on value. people might find overkill, use function creates classes based on input.
whatever though, way have now, running raw, user-input strings using exec, bad idea. best case scenario introduces new bugs near-impossible trace since aren't recorded anywhere. worst case scenario, user somehow finds way send string function, you've pretty destroyed whatever security you've hoped for.
basically "exec" should last resort. there more elegant , secure ways solve problem.
Comments
Post a Comment