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

为何运行Python代码时未显示DeprecationWarning弃用警告信息

Why isn't my DeprecationWarning showing up in Python?

Hey there! I totally get why this is confusing—you’ve set up the warning call correctly, but it’s nowhere to be seen. Let’s break down what’s going on and fix it.

The Root Cause

Python suppresses DeprecationWarning messages by default. These warnings are designed for library developers to spot outdated code, so the default warning filter hides them to avoid cluttering end-users’ output. That’s why you only see your print statement, but no warning text.

Fixes to Make the Warning Visible

You’ve got a few straightforward ways to enable the warning:

1. Enable Warnings via Command Line

When running your script, add the -W default flag to tell Python to show default warnings (including DeprecationWarning):

python -W default your_script_name.py

2. Modify the Warning Filter in Your Code

Add a line right after importing warnings to explicitly enable DeprecationWarning for your script:

import warnings
# Turn on DeprecationWarning display
warnings.filterwarnings("default", category=DeprecationWarning)

def deprecate_something(arg1):
    arguments_by_list = do_something(arg1)
    print("Running deprecation check on arg1")
    warnings.warn(
        f"""
        arg1 attribute is deprecated. use {arguments_by_list}
        """,
        DeprecationWarning,
    )
    return arg1

# Example do_something function (since it wasn't defined in your original code)
def do_something(arg):
    return f"new_arg={arg}"

deprecate_something("HelloWorld")

This ensures the warning shows up every time the script runs.

3. Use warnings.simplefilter for a Global Toggle

If you want to force all DeprecationWarnings to be displayed (not just this specific one), use simplefilter:

warnings.simplefilter('always', DeprecationWarning)

This overrides the default filter and makes every warning in the DeprecationWarning category visible.

What You’ll See After Fixing

Once you apply any of these changes, your output should look like this:

Running deprecation check on arg1
__main__.py:10: DeprecationWarning: 
        arg1 attribute is deprecated. use new_arg=HelloWorld
        
  warnings.warn(

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 04:27:46