Displaying Content of Each Code Line

Hi. How can I view the results of each code line?
For example I want to know what the results are this line-- “for name in obj.__dict__keys():”

Thank you.

class MyClass:
    pass

obj = MyClass()
obj.a = 1
obj.b = 2
obj.i = 3
obj.ireal = 3.5
obj.integer = 4
obj.z = 5

def IncIntsI(obj):
    for name in obj.__dict__.keys():
        if name.startswith('i'):
            val = getattr(obj,name)
            if isinstance(val,int):
                setattr(obj,name,val+1)

I know the results… but just asking in general… how to show that line’s results? Thanks.

I would add print() statements to output values of interest and give clues to the flow of control.

For this case add the print as the first line inside the for loop.

    for name in obj.__dict__.keys():
        print(f’name {name}’)
        if name.startswith('i'):
1 Like

With a well featured IDE, you can “single step” through your Python script and examine the the data as you go.

1 Like

Function is only defined and not called. Therefore I wonder what should be the result of each code line in function definition.

1 Like

Do you mean what is the function’s statements compiled into?
You can use the dis module to view the python byte code.

If that is not what you mean you will have to tell us more details so that we can understand the question.

There are online services that can help visualize what is happening when the code runs, such as https://pythontutor.com/ . But lines of code do not have “content” or “results”. When each part of the code runs, the result depends on the “environment” (values of all the variables that the code can access; if it can read files then it depends on the file system; if it can check the operating system’s environment variables then it depends on those, etc.) And when the code is running, it is in a compiled form. There is some support for figuring out the line of code that an instruction came from, but the code does not actually run “a line at a time”.

You might be able to do this with settrace: sys — System-specific parameters and functions — Python 3.12.0 documentation