You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Visual Studio Code中设置断点追踪对象属性变更?

如何在ip_address字段变更时触发调试断点

可以通过几种方式实现,直接上具体方案:

1. 修改User类,给ip_address加监控断点

如果user是你自定义的类,直接把ip_address改成带setter的属性,在赋值时检查值并触发断点:

import pdb

class User:
    def __init__(self, ip_address):
        self._ip_address = ip_address

    @property
    def ip_address(self):
        return self._ip_address

    @ip_address.setter
    def ip_address(self, value):
        # 只要被设为None就暂停
        if value is None:
            pdb.set_trace()
        self._ip_address = value

这样每次ip_address被赋值为None时,调试器会自动停下来。

2. 用IDE的条件断点(不用改代码)

如果知道ip_address在哪里被赋值,直接在那一行加条件断点:

  • 找到赋值代码行(比如user.ip_address = xxx)
  • 设置断点的触发条件为xxx is None(替换成实际的赋值变量名)
  • 启动调试,满足条件时就会暂停

要是不知道具体赋值位置,用Python自带的追踪功能全局监控:

import sys

def trace_assignments(frame, event, arg):
    if event == 'line':
        code = frame.f_code
        # 检查当前行是否涉及ip_address的赋值
        if 'ip_address' in code.co_names:
            user = frame.f_locals.get('user')
            if user and user.ip_address is not None:
                # 赋值完成后检查是否变None
                def check_after_assign():
                    if user.ip_address is None:
                        import pdb; pdb.set_trace()
                # 临时追踪下一行的返回事件,触发检查
                sys.settrace(lambda f,e,a: check_after_assign() if e == 'return' else None)
    return trace_assignments

# 启动应用前开启追踪
sys.settrace(trace_assignments)

3. 调试器里加Watch表达式

在IDE调试会话中,添加Watch表达式request.user.ip_address,然后设置触发规则:

  • VS Code:右键Watch表达式,选「Conditional Breakpoint」,条件设为request.user.ip_address is None
  • PyCharm:右键Watch表达式,选「Break when value changes」,再设置过滤条件为值等于None

内容的提问来源于stack exchange,提问作者Philippe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:43:32