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

Python中bool_dir用法咨询:旧代码中发现的已废弃工具

About bool_dir from the deprecated tools module

我之前在维护旧Python项目时也碰到过这个废弃的bool_dir函数,刚好能给你梳理清楚它的用法和替代方案:

What bool_dir did

bool_dir是早年一个小众Python工具库tools里的函数,这个库现在已经被废弃,官方推荐用weblib替代。它的核心作用是对内置dir()函数的结果做筛选,让输出更简洁:

  • 自动过滤掉对象中所有以双下划线__开头且结尾的特殊属性/方法(比如__init__、__dict__这类Python内置的魔法方法)
  • 部分版本还会额外筛选出属性值为布尔类型(bool)或者能被隐式转换为布尔值的属性(这个特性在不同版本的tools库中略有差异)
  • 返回经过精简的属性列表,方便调试或者动态访问对象属性

Typical Usage Example

假设你有一个自定义类:

class User:
    def __init__(self):
        self.name = "Alice"
        self.is_active = True
        self.age = 30
        self._internal_status = False  # 单下划线的私有属性不会被过滤

    def send_greeting(self):
        return f"Hi, I'm {self.name}"

用bool_dir调用的话:

from tools import bool_dir

user = User()
print(bool_dir(user))

输出大概是这样(基础版本,只过滤特殊属性):

['_internal_status', 'age', 'is_active', 'name', 'send_greeting']

如果是带布尔值过滤的版本,输出可能会是['_internal_status', 'is_active']——不过大部分场景下,它的核心还是排除那些魔法属性。

Replacement: Use dir2 from weblib

因为tools库已经没人维护了,现在可以用weblib里的dir2函数来替代,它完全继承了bool_dir的核心逻辑,还增加了更多自定义选项:

首先安装weblib:

pip install weblib

然后使用:

from weblib import dir2

user = User()
print(dir2(user))

dir2支持更多参数,比如你可以指定是否包含单下划线的私有属性、是否只返回方法或只返回属性,比旧的bool_dir灵活很多。

Manual Implementation (No Third-Party Dependency)

如果不想引入新的依赖,也可以自己写一个简单的替代函数,实现最基础的筛选功能:

def bool_dir(obj):
    # 过滤掉双下划线包裹的特殊属性
    return [attr for attr in dir(obj) if not (attr.startswith('__') and attr.endswith('__'))]

如果需要筛选出布尔值属性,可以扩展成这样:

def bool_dir(obj):
    filtered_attrs = []
    for attr in dir(obj):
        if not (attr.startswith('__') and attr.endswith('__')):
            try:
                attr_value = getattr(obj, attr)
                if isinstance(attr_value, bool):
                    filtered_attrs.append(attr)
            except AttributeError:
                # 处理无法获取属性的情况
                continue
    return filtered_attrs

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:06:59