How do edits count during debug?

Asked

Viewed 65 times

2

When I am debugging a code in Pycharm (Shift+F9) and make some changes, it is not recognized during the same debug session. I am obliged to restart the debug again for the changes to be recognized.

Is there any way that Pycharm recognizes changes DURING debug?

1 answer

2


It would be nice if you put an example of what variables you’re trying to change. But anyway, if you are trying to change local variables in a debugging function, this is not possible because of how Python is implemented:

The internal mechanisms of the language itself that allow debugging and others, always update the local variables in a "read only" way: the debugger or any function called can see the local variables accessing the attribute f_locals the execution frame of the function being inspected.

However, although up to version 3.7, f_locals contains a standard dictionary, which allows changing the values, these values nay are copied back to the local function variables when it actually runs. This until today was more or less an "implementation detail" of Cpython, indicated in some parts of the documentation - but is being formalized as part of the language specification in the PEP 558.

In short: neither pycharm’s Debugger, nor any other Debugger, nor any functionality that does not violate language specifications to do "magic" in values of a function that calls others (explicitly, or implicitly, as is the case in debugger operation), can change the value of a local variable.

However, if you need this to streamline your workflow, there is a workaround: objects that are associated with names in local variables cannot be change, but may be altered. That is, if your variable content is a number or a string, there is nothing that can be done. But if your content is a list, dictionary, or other mutable object, this object can be changed from the context of the debuggers.

So, let’s assume that your function has a variable id that you would like to be able to interactively change from within the Debugger - you can (maybe temporarily) change your code so that the values that interest you are within a list:

Instead of:

def minha_func(id):
   ...
   consulta_ao_banco(id)
   ...

You can do:

def minha_func(id):
   id = [id]
   ...
   # neste trecho do código, o conteúdo da lista em 'id' pode 
   # ser alterado de dentro do debugger
   ...
   consulta_ao_banco(id[0])
   ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.