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

使用Babel 2.12.1获取货币符号时遇AttributeError: module 'babel' has no attribute 'numbers'

解决Babel 2.12.1版本中AttributeError: module 'babel' has no attribute 'numbers'的问题

问题背景

需求是传入区域代码获取对应货币符号,使用Babel 2.12.1版本时触发属性错误,原代码及报错详情如下:

原代码

import babel

def get_currency_symbol(locale_code):
    try:
        return babel.numbers.get_currency_symbol(None, locale_code)
    except babel.core.UnknownLocaleError:
        print(f"Invalid locale code: {locale_code}")
        return '$'

print(get_currency_symbol('en_US'))
print(get_currency_symbol('fr_FR'))
print(get_currency_symbol('invalid_locale'))

报错信息

(venv) me@VKY7WPYWV1 project % python tools/del.py
Traceback (most recent call last):
  File "/Users/me/GitHub/lumada-catalog/project/tools/del.py", line 7, in <module>
    print(get_currency_symbol('en_US'))
  File "/Users/me/GitHub/lumada-catalog/project/tools/del.py", line 4, in get_currency_symbol
    return babel.numbers.get_currency_symbol(None, locale_code)
AttributeError: module 'babel' has no attribute 'numbers'

解决方法

Babel的子模块不会自动通过主模块babel暴露,必须显式导入对应子模块。修正后的代码如下:

from babel.numbers import get_currency_symbol
from babel.core import UnknownLocaleError

def get_currency_symbol(locale_code):
    try:
        # 按文档要求,通过关键字参数指定区域,无需传currency参数
        return get_currency_symbol(locale=locale_code)
    except UnknownLocaleError:
        print(f"无效的区域代码: {locale_code}")
        return '$'

print(get_currency_symbol('en_US'))  # 输出 $
print(get_currency_symbol('fr_FR'))  # 输出 €
print(get_currency_symbol('invalid_locale'))  # 打印错误信息并返回 $

关键修改点

  1. 显式导入子模块:直接导入babel.numbers下的目标函数和babel.core下的异常类,避免通过主模块间接访问子模块。
  2. 修正参数传递方式:原代码参数顺序不符合文档规范,get_currency_symbol的默认参数顺序是(currency, locale),若无需指定货币,应通过关键字参数locale=locale_code传递区域信息。

验证结果

运行修正后的代码,会正确输出对应区域的货币符号;传入无效区域代码时,会触发异常处理逻辑,打印提示信息并返回默认符号$。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 12:47:29