- Функция breakpoint() в Python
- Как работает функция breakpoint() в Python?
- PYTHONBREAKPOINT
- Как изменить модуль отладчика?
- breakpoint() in Python
- Why Breakpoint in Python?
- Syntax of breakpoint() Function in Python
- Parameters of breakpoint() Function in Python
- Return Value of breakpoint() Function in Python
- Exceptions of the Breakpoint in Python
- How does Breakpoint in Python Work?
- Examples of a Breakpoint in Python
- Conclusion
- Learn More:
Функция breakpoint() в Python
breakpoint() в Python – это новая встроенная функция, представленная в Python 3.7. Отладка кода всегда была болезненным процессом из-за тесной связи между фактическим кодом и кодом модуля отладки.
Например, если вы используете отладчик pdb, вам придется вызвать pdb.set_trace() в своем программном коде. Если вы хотите использовать любой другой отладчик, скажем, web-pdb, тогда вам придется удалить весь код, связанный с PDB, и добавить метод web_pdb.set_trace(). Это приводит к огромным накладным расходам при использовании отладчика Python и затрудняет отладку и обслуживание кода.
Вот почему Python 3.7 представил метод breakpoint(), который позволяет нам писать слабо связанный код отладки.
Как работает функция breakpoint() в Python?
Функция breakpoint() вызывает функцию sys.breakpointhook(). По умолчанию sys.breakpointhook() вызывает функцию pdb.set_trace(). Так что, по крайней мере, использование breakpoint() обеспечивает удобство использования отладчика, потому что нам не нужно явно импортировать модуль pdb.
Давайте посмотрим на простой пример использования функции breakpoint(). У нас есть скрипт python_breakpoint_examples.py со следующим кодом.
x = 10 y = 'Hi' z = 'Hello' print(y) breakpoint() print(z)
Когда мы выполняем этот скрипт, открывается консоль отладчика PDB.
$python3.7 python_breakpoint_examples.py Hi > /Users/pankaj/Documents/PycharmProjects/BasicPython/basic_examples/python_breakpoint_examples.py(8)() -> print(z) (Pdb) c Hello $
PYTHONBREAKPOINT
Функция Python sys.breakpointhook() использует переменную среды PYTHONBREAKPOINT для настройки отладчика. Если не установлено, используется отладчик PDB по умолчанию.
Если установлено значение «0», функция немедленно возвращается, и отладка кода не выполняется. Это очень полезно, когда мы хотим запустить наш код без отладки.
$PYTHONBREAKPOINT=0 python3.7 python_breakpoint_examples.py Hi Hello $
Как изменить модуль отладчика?
Мы можем использовать переменную среды PYTHONBREAKPOINT, чтобы предоставить метод отладчика, который будет вызываться функцией breakpoint(). Это очень полезно, потому что мы можем легко изменить модуль отладчика, не внося никаких изменений в код.
Допустим, мы хотим использовать отладчик web-pdb. Мы можем легко подключить его к нашей программе, используя PYTHONBREAKPOINT = web_pdb.set_trace.
Прежде всего, убедитесь, что установлен web-pdb. Вы можете установить его с помощью команды pip3.7 install web-pdb.
$PYTHONBREAKPOINT=web_pdb.set_trace python3.7 python_breakpoint_examples.py Hi 2018-08-10 12:49:54,339: root - web_console:110 - CRITICAL - Web-PDB: starting web-server on pankaj:5555.
Откройте URL-адрес веб-сервера, указанный в журнале консоли, и вы увидите окно отладчика, подобное изображению ниже.
Мы можем выдавать команды PDB с помощью этого пользовательского интерфейса, вы можете отправить команду «c», чтобы продолжить и завершить нашу программу.
breakpoint() in Python
While coding in Python, we encounter errors caused due to one or another error in the code or by the code. To help us mitigate the long tiring process of finding out where exactly the code raised an error and help us effectively being and evaluate the working of the code the breakpoint() in Python was introduced.
Why Breakpoint in Python?
Let us understand the problem statement for breakpoint() in Python.
When we debug through the code, previously we use to do so by first importing the pdb module and then using the method using pdb.set_trace() which helped us fetch the contents of your environment and all the associated variables. But the process of debugging became very time-consuming and was not seeming intuitive to developers to import a module and set the method every time.
To combat this issue of importing the pdb module and calling the method pdb.set_trace() , with the 3.7 version Python introduced the breakpoint() in Python.
The breakpoint() in Python is defined as the effective way of analyzing our code to check for errors that are encountered while executing the program. Whenever we want to debug through the entire code or want to pause the code to test if the lines of code until the breakpoint() in Python are working fine, we use the breakpoint() in Python syntax.
The breakpoint() in Python calls the function sys.breakpointhook() from the sys module which helps to make an entry into the pdb session. The syntax of the breakpoint in the Python function is: breakpoint(*args, **kwargs) . Sometimes it is also seen that you may encounter a TypeError exception which arises when the signature between the positional and keyword arguments passed through the sys.breakpointhook() does not match.
Syntax of breakpoint() Function in Python
The syntax for breakpoint() in Python is stated below:
Above we saw how we can make use of the breakpoint() in Python for versions above Python ‘3.7’ and below Python ‘3.6’.
Parameters of breakpoint() Function in Python
The optional parameters that we may pass in the breakpoint() in Python syntax are
- *args (Non-Keyword Arguments)
- **kwargs(Keyword Arguments) where the number of arguments that can be passed is not defined.
Return Value of breakpoint() Function in Python
The return value that we get as output through the breakpoint() in Python is that the code gets paused at the place where we have used this method. The code will not get executed until we remove the breakpoint( ) in Python.
Exceptions of the Breakpoint in Python
There are no exceptions when we use the breakpoint() in Python. The breakpoint() in Python is widely used to tackle the error raised in the code via ‘exception handling’ or while ‘debugging in code’. By implementing breakpoint() in Python, the code’s execution gets paused where ever we stated the breakpoint() in Python which allows us to conveniently check for issues in the code.
How does Breakpoint in Python Work?
While working with breakpoint() in Python, we conveniently and effectively get into the debugger mode without the hassle we used to face with the older version of Python( to import the pdb module and call the pdb.settrace() method).
Now with Python 3.7 version, we can use the breakpoint() in Python. But how can we shorten the time-consuming process, let us discuss that.
The breakpoint() in Python calls the function sys.breakpointhook() which uses the environment variable PYTHONBREAKPOINT . The sys.breakpointhook() calls the pdb.set_trace() function by default whereas we used the PYTHONBREAKPOINT when we want to switch between the debugging modes.
When the PYTHONBREAKPOINT variable is disabled ( set to 0) then the pdb debugger does not get utilized when we call for the breakpoint() in Python which disables the debugging process. Hence, we can simply unset this environment variable for breakpoint() in Python code used in the entire program when we are not looking forward to debugging the code.
Below diagram shows how breakpoint() in Python works and how the backend process gets called:
Examples of a Breakpoint in Python
Below we have a few simple code examples of breakpoint() in Python function usage.
Code example 1: Demonstrating how we used to implement the debugging before the Python 3.7 version
The below code explains how we did debug using the pdb.set_trace() method, which used to be lengthy as well required the pdb module to be imported each time.
Explanation: Above code, we demonstrated how we used to implement the debugging before the Python 3.7 version. We started by improving the pdb module. Here when the value of variable ‘u’ is up to 7, it gets printed which is implemented by using the for loop in Python. We implemented the if condition where when the value of variable ‘u’ is equal to 7 then the print statement gets printed where it calls the variable ‘t’ which is having the string ‘hello there!’.
But once the if condition is satisfied to be equal to 12 then we enforced the debugging using the pdb.settrace() method which we used to implement before breakpoint() in Python was introduced.
Code example 2: A simple code to demonstrate breakpoint() in Python.
Below code, example explains how the if-else condition works when the condition is validated to be ‘TRUE’, whereas once we put the breakpoint() syntax even if the if-else condition is validated to be ‘TRUE’ still the code execution gets paused.
Explanation: Above code, we demonstrated how a simple addition program was executed using the if-else loop. When the sum was less than or equal to 5, the print statement got printed. But to debug the code we implemented the breakpoint() in Python which didn’t let the print statement get executed( as the sum was less than 7) as the breakpoint() in Python was used before it.
Code Example 3: Using for loop to demonstrate how we can easily debug using breakpoint() in Python
Below code, example explains how the for-loop condition works when the condition is validated to be ‘TRUE’, whereas once we put the breakpoint() syntax even if the for loop condition is validated to be ‘TRUE’ still the code execution gets paused.
Explanation: Above code, we demonstrated how we can debug when a program was executed using the for loop along with if-else conditions. When the sum was in the range of 7, the print statement got printed for the first part of the code. But to debug the code we implemented the breakpoint() in Python which didn’t let the print statement get executed (as the sum was in the range till 7) as the breakpoint() in Python was used before it.
Conclusion
Let’s sum up the entire article into a few important takeaways:
- The breakpoint() in Python is defined as the effective way of analyzing our code to check for error that is encountered while executing the program. Whenever we want to debug through the entire code or want to pause the code to test if the lines of code until the breakpoint() in Python are working fine, we use the breakpoint() in Python syntax.
- The breakpoint() in Python calls the function sys.breakpointhook() from the sys module which helps to make an entry into the pdb session. The syntax of the breakpoint in the Python function is: breakpoint(*args, **kwargs) .
- The breakpoint() in Python calls the function sys.breakpointhook() which uses the environment variable PYTHONBREAKPOINT by calling the pdb.set_trace() function by default which then points to the environment variable PYTHONBREAKPOINT .