When I have exec() in defined function it is not working ('NameError: name 'a' is not defined'):
def abc():
qwerty = "a = 2"
exec(qwerty)
abc()
print(a)
but, when I won't use def, it is working:
qwerty = "a = 2"
exec(qwerty)
print(a)
How can I "repair" it, or are there other similar solutions? (I can't execute this at start, I need to call that function in the middle of the program)
a = 2inside the function, it gets defined in the local scope, then once you get toprint(a)you are outside that scope. You could probably declare the variable global at the start ofabc.execshould almost never be used unless you are absolutely sure it's the only and correct solution. Many new programmers learn aboutexecorevaland think they are solutions to their problems, when 99.99% of the time there are much better ways to solve your problem. Code withexecandevalusually becomes very hard to read or understand for a professional programmer, and they potentially creates many security issues in your program. They're also slower than the alternatives. I've yet to ever needed to use, or seen, them in a production program.