"bdb" --- Debugger framework
****************************

**Kod źródłowy:** Lib/bdb.py

======================================================================

Модуль "bdb" обробляє основні функції налагоджувача, як-от
встановлення точок зупину або керування виконанням через налагоджувач.

Визначено такий виняток:

exception bdb.BdbQuit

   Виняток, створений класом "Bdb" для виходу з налагоджувача.

Модуль "bdb" також визначає два класи:

class bdb.Breakpoint(self, file, line, temporary=False, cond=None, funcname=None)

   Цей клас реалізує тимчасові точки зупинки, ігнорування підрахунків,
   відключення та (повторне) увімкнення, а також умови.

   Точки зупину індексуються за номером у списку під назвою
   "bpbynumber" та парами "(файл, рядок)" через "bplist". Перший
   вказує на єдиний екземпляр класу "Breakpoint". Останній вказує на
   список таких випадків, оскільки на рядок може бути більше однієї
   точки зупину.

   When creating a breakpoint, its associated "file name" should be in
   canonical form.  If a "funcname" is defined, a breakpoint "hit"
   will be counted when the first line of that function is executed.
   A "conditional" breakpoint always counts a "hit".

   Екземпляри "Breakpoint" мають такі методи:

   deleteMe()

      Видалити точку зупину зі списку, пов’язаного з файлом/рядком.
      Якщо це остання точка зупину в цій позиції, вона також видаляє
      запис для файлу/рядка.

   enable()

      Позначте точку зупину як увімкнену.

   disable()

      Позначте точку зупину як вимкнену.

   bpformat()

      Повертає рядок з усією інформацією про точку зупину, красиво
      відформатований:

      * Breakpoint number.

      * Temporary status (del or keep).

      * File/line position.

      * Break condition.

      * Number of times to ignore.

      * Number of times hit.

       Dodane w wersji 3.2.

   bpprint(out=None)

      Надрукувати вихідні дані "bpformat()" у файл *out*, або, якщо
      він "None", у стандартний вихід.

   "Breakpoint" instances have the following attributes:

   file

      File name of the "Breakpoint".

   line

      Line number of the "Breakpoint" within "file".

   temporary

      "True" if a "Breakpoint" at (file, line) is temporary.

   cond

      Condition for evaluating a "Breakpoint" at (file, line).

   funcname

      Function name that defines whether a "Breakpoint" is hit upon
      entering the function.

   enabled

      "True" if "Breakpoint" is enabled.

   bpbynumber

      Numeric index for a single instance of a "Breakpoint".

   bplist

      Dictionary of "Breakpoint" instances indexed by ("file", "line")
      tuples.

   ignore

      Number of times to ignore a "Breakpoint".

   hits

      Count of the number of times a "Breakpoint" has been hit.

class bdb.Bdb(skip=None, backend='settrace')

   Клас "Bdb" діє як загальний базовий клас налагоджувача Python.

   Цей клас піклується про деталі засобу трасування; похідний клас
   повинен реалізовувати взаємодію з користувачем. Прикладом є
   стандартний клас відладчика ("pdb.Pdb").

   Аргумент *skip*, якщо він наданий, має бути повторюваним шаблоном
   імен модулів у стилі glob. Налагоджувач не ввійде в кадри, які
   походять із модуля, який відповідає одному з цих шаблонів. Чи
   вважається, що фрейм походить із певного модуля, визначається
   "__name__" у глобальних параметрах фрейму.

   The *backend* argument specifies the backend to use for "Bdb". It
   can be either "'settrace'" or "'monitoring'". "'settrace'" uses
   "sys.settrace()" which has the best backward compatibility. The
   "'monitoring'" backend uses the new "sys.monitoring" that was
   introduced in Python 3.12, which can be much more efficient because
   it can disable unused events. We are trying to keep the exact
   interfaces for both backends, but there are some differences. The
   debugger developers are encouraged to use the "'monitoring'"
   backend to achieve better performance.

   Zmienione w wersji 3.1: Added the *skip* parameter.

   Zmienione w wersji 3.14: Added the *backend* parameter.

   Наступні методи "Bdb" зазвичай не потребують перевизначення.

   canonic(filename)

      Return canonical form of *filename*.

      For real file names, the canonical form is an operating-system-
      dependent, "case-normalized" "absolute path". A *filename* with
      angle brackets, such as ""<stdin>"" generated in interactive
      mode, is returned unchanged.

   start_trace(self)

      Start tracing. For "'settrace'" backend, this method is
      equivalent to "sys.settrace(self.trace_dispatch)"

       Dodane w wersji 3.14.

   stop_trace(self)

      Stop tracing. For "'settrace'" backend, this method is
      equivalent to "sys.settrace(None)"

       Dodane w wersji 3.14.

   reset()

      Set the "botframe", "stopframe", "returnframe" and "quitting"
      attributes with values ready to start debugging.

   trace_dispatch(frame, event, arg)

      Ця функція встановлена як функція трасування налагоджених
      кадрів. Його значенням, що повертається, є нова функція
      трасування (у більшості випадків, тобто сама).

      Реалізація за замовчуванням вирішує, як відправляти кадр,
      залежно від типу події (переданої у вигляді рядка), яка має бути
      виконана. *подією* може бути одне з наступного:

      * ""рядок"": буде виконано новий рядок коду.

      * ""виклик"": функція буде викликана або введено інший блок
        коду.

      * ""return"": функція або інший блок коду збирається
        повернутися.

      * ""exception"": сталася виняток.

      * ""c_call"": функція C збирається викликатися.

      * ""c_return"": функція C повернулася.

      * ""c_exception"": функція C викликала виняток.

      Для подій Python викликаються спеціалізовані функції (див.
      нижче). Для подій C не виконується жодних дій.

      Параметр *arg* залежить від попередньої події.

      Перегляньте документацію для "sys.settrace()", щоб дізнатися
      більше про функцію трасування. Для отримання додаткової
      інформації про код і об’єкти фрейму зверніться до The standard
      type hierarchy.

   dispatch_line(frame)

      If the debugger should stop on the current line, invoke the
      "user_line()" method (which should be overridden in subclasses).
      Raise a "BdbQuit" exception if the "quitting" flag is set (which
      can be set from "user_line()").  Return a reference to the
      "trace_dispatch()" method for further tracing in that scope.

   dispatch_call(frame, arg)

      If the debugger should stop on this function call, invoke the
      "user_call()" method (which should be overridden in subclasses).
      Raise a "BdbQuit" exception if the "quitting" flag is set (which
      can be set from "user_call()").  Return a reference to the
      "trace_dispatch()" method for further tracing in that scope.

   dispatch_return(frame, arg)

      If the debugger should stop on this function return, invoke the
      "user_return()" method (which should be overridden in
      subclasses). Raise a "BdbQuit" exception if the "quitting" flag
      is set (which can be set from "user_return()").  Return a
      reference to the "trace_dispatch()" method for further tracing
      in that scope.

   dispatch_exception(frame, arg)

      If the debugger should stop at this exception, invokes the
      "user_exception()" method (which should be overridden in
      subclasses). Raise a "BdbQuit" exception if the "quitting" flag
      is set (which can be set from "user_exception()").  Return a
      reference to the "trace_dispatch()" method for further tracing
      in that scope.

   Зазвичай похідні класи не замінюють наступні методи, але вони
   можуть, якщо хочуть перевизначити визначення зупинки та точок
   зупинки.

   is_skipped_module(module_name)

      Return "True" if *module_name* matches any skip pattern.

   stop_here(frame)

      Return "True" if *frame* is below the starting frame in the
      stack.

   break_here(frame)

      Return "True" if there is an effective breakpoint for this line.

      Check whether a line or function breakpoint exists and is in
      effect.  Delete temporary breakpoints based on information from
      "effective()".

   break_anywhere(frame)

      Return "True" if any breakpoint exists for *frame*'s filename.

   Похідні класи повинні перевизначати ці методи, щоб отримати
   контроль над роботою відладчика.

   user_call(frame, argument_list)

      Called from "dispatch_call()" if a break might stop inside the
      called function.

      *argument_list* is not used anymore and will always be "None".
      The argument is kept for backwards compatibility.

   user_line(frame)

      Called from "dispatch_line()" when either "stop_here()" or
      "break_here()" returns "True".

   user_return(frame, return_value)

      Called from "dispatch_return()" when "stop_here()" returns
      "True".

   user_exception(frame, exc_info)

      Called from "dispatch_exception()" when "stop_here()" returns
      "True".

   do_clear(arg)

      Визначте, як потрібно видалити точку зупину, якщо вона є
      тимчасовою.

      Цей метод має бути реалізований похідними класами.

   Похідні класи та клієнти можуть викликати наступні методи, щоб
   впливати на кроковий стан.

   set_step()

      Зупинка після одного рядка коду.

   set_next(frame)

      Зупиніться на наступному рядку в заданому кадрі або під ним.

   set_return(frame)

      Зупинка при поверненні із заданого кадру.

   set_until(frame, lineno=None)

      Stop when the line with the *lineno* greater than the current
      one is reached or when returning from current frame.

   set_trace([frame])

      Почніть налагодження з *фрейму*. Якщо *frame* не вказано,
      налагодження починається з кадру абонента.

      Zmienione w wersji 3.13: "set_trace()" will enter the debugger
      immediately, rather than on the next line of code to be
      executed.

   set_continue()

      Зупиняйтеся лише в точках зупинки або після завершення. Якщо
      немає контрольних точок, встановіть для функції трасування
      системи значення "None".

   set_quit()

      Set the "quitting" attribute to "True".  This raises "BdbQuit"
      in the next call to one of the "dispatch_*()" methods.

   Похідні класи та клієнти можуть викликати наведені нижче методи для
   керування точками зупинки. Ці методи повертають рядок, що містить
   повідомлення про помилку, якщо щось пішло не так, або "None", якщо
   все добре.

   set_break(filename, lineno, temporary=False, cond=None, funcname=None)

      Встановіть нову точку зупинки. Якщо рядок *lineno* не існує для
      *ім’я файлу*, переданого як аргумент, поверніть повідомлення про
      помилку. *Ім’я* файлу має бути в канонічній формі, як описано в
      методі "canonic()".

   clear_break(filename, lineno)

      Delete the breakpoints in *filename* and *lineno*.  If none were
      set, return an error message.

   clear_bpbynumber(arg)

      Видаліть точку зупину, яка має індекс *arg* у
      "Breakpoint.bpbynumber". Якщо *arg* не є числом або виходить за
      межі діапазону, повертає повідомлення про помилку.

   clear_all_file_breaks(filename)

      Delete all breakpoints in *filename*.  If none were set, return
      an error message.

   clear_all_breaks()

      Delete all existing breakpoints.  If none were set, return an
      error message.

   get_bpbynumber(arg)

      Повертає точку зупину, визначену заданим числом. Якщо *arg* є
      рядком, його буде перетворено на число. Якщо *arg* є нечисловим
      рядком, якщо задана точка зупину ніколи не існувала або була
      видалена, виникає "ValueError".

       Dodane w wersji 3.2.

   get_break(filename, lineno)

      Return "True" if there is a breakpoint for *lineno* in
      *filename*.

   get_breaks(filename, lineno)

      Повертає всі контрольні точки для *lineno* в *імені файлу* або
      порожній список, якщо жодна з них не встановлена.

   get_file_breaks(filename)

      Повертає всі контрольні точки в *назві файлу* або порожній
      список, якщо жодна з них не встановлена.

   get_all_breaks()

      Повернути всі встановлені точки зупину.

   Derived classes and clients can call the following methods to
   disable and restart events to achieve better performance. These
   methods only work when using the "'monitoring'" backend.

   disable_current_event()

      Disable the current event until the next time "restart_events()"
      is called. This is helpful when the debugger is not interested
      in the current line.

       Dodane w wersji 3.14.

   restart_events()

      Restart all the disabled events. This function is automatically
      called in "dispatch_*" methods after "user_*" methods are
      called. If the "dispatch_*" methods are not overridden, the
      disabled events will be restarted after each user interaction.

       Dodane w wersji 3.14.

   Похідні класи та клієнти можуть викликати наведені нижче методи,
   щоб отримати структуру даних, що представляє трасування стека.

   get_stack(f, t)

      Return a list of (frame, lineno) tuples in a stack trace, and a
      size.

      The most recently called frame is last in the list. The size is
      the number of frames below the frame where the debugger was
      invoked.

   format_stack_entry(frame_lineno, lprefix=': ')

      Return a string with information about a stack entry, which is a
      "(frame, lineno)" tuple.  The return string contains:

      * The canonical filename which contains the frame.

      * The function name or ""<lambda>"".

      * Вхідні аргументи.

      * Повернене значення.

      * Рядок коду (якщо він існує).

   Наступні два методи можуть бути викликані клієнтами для
   використання налагоджувача для налагодження *statement*, поданого
   як рядок.

   run(cmd, globals=None, locals=None)

      Debug a statement executed via the "exec()" function.  *globals*
      defaults to "__main__.__dict__", *locals* defaults to *globals*.

   runeval(expr, globals=None, locals=None)

      Налагодити вираз, що виконується за допомогою функції "eval()".
      *globals* і *locals* мають те саме значення, що й у "run()".

   runctx(cmd, globals, locals)

      Для зворотної сумісності. Викликає метод "run()".

   runcall(func, /, *args, **kwds)

      Налагодити один виклик функції та повернути його результат.

Нарешті, модуль визначає такі функції:

bdb.checkfuncname(b, frame)

   Return "True" if we should break here, depending on the way the
   "Breakpoint" *b* was set.

   If it was set via line number, it checks if "b.line" is the same as
   the one in *frame*. If the breakpoint was set via "function name",
   we have to check we are in the right *frame* (the right function)
   and if we are on its first executable line.

bdb.effective(file, line, frame)

   Return "(active breakpoint, delete temporary flag)" or "(None,
   None)" as the breakpoint to act upon.

   The *active breakpoint* is the first entry in "bplist" for the
   ("file", "line") (which must exist) that is "enabled", for which
   "checkfuncname()" is true, and that has neither a false "condition"
   nor positive "ignore" count.  The *flag*, meaning that a temporary
   breakpoint should be deleted, is "False" only when the "cond"
   cannot be evaluated (in which case, "ignore" count is ignored).

   If no such entry exists, then "(None, None)" is returned.

bdb.set_trace()

   Почніть налагодження з екземпляра "Bdb" із фрейму абонента.
