I have a python function and I want it to be executed after every statement that is executed anyway. Is there a way to do it without manually writing it under every statement?
Asked
Active
Viewed 49 times
-2
-
7Why do you want this? It sounds like an [XY problem](https://xyproblem.info/). – kaya3 Oct 23 '22 at 13:51
-
1Is this for debugging purposes? – luk2302 Oct 23 '22 at 13:53
-
3"Line of code" isn't really a useful "chunk" of Python. Your code consists of a series of *statements*, each of which could span multiple lines. – chepner Oct 23 '22 at 13:55
-
@chepner isn't a _statement_ usually separated from another using a line break? I guess you're right that I could separate my statement with a backslash but I presumed it was pretty obvious - will edit my question regardless. – T. F. Oct 23 '22 at 14:02
-
Usually, but not always. `x = 1; y = 2` is a single line with two statements. (Only *simple* statements can be separated by a `;` on a single line.) But there are also compound statements (`if`, `while`, etc) that are single statements that can (and usually do) span multiple lines. – chepner Oct 23 '22 at 14:04
-
I suppose, yea. Do you know how this could be achieved? – T. F. Oct 23 '22 at 14:06
-
I think this could help: https://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python – Swifty Oct 23 '22 at 14:10
-
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 23 '22 at 14:13
1 Answers
0
Here's an example of something that leans towards what you want (there are probably better/cleaner ways)
mycode= '''
print("Hello World :)")
a = 5
x = a+2
print(a, x)
'''
def my_func():
print("Test".center(30,"-"))
for line in mycode.splitlines():
if not line.strip(): continue # skips empty lines
exec(line)
my_func()

Swifty
- 2,630
- 2
- 3
- 21