You need to enable JavaScript to run this app. Python 3.9.6中如何按参数从NamedTuple类型配置中获取指定键值对
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.9.6中如何按参数从NamedTuple类型配置中获取指定键值对

从TOML生成的NamedTuple配置中动态提取指定参数的方案

场景说明

使用Python 3.9.6版本开发时,读取TOML配置文件生成了NamedTuple类型的配置对象,可直接从config模块导入configuration实例,配置结构如下:

from config import configuration

"""
[discord]
    [discord.filtered]
        [[discord.filtered.swedish]]
            eu = "https://discordapp.com/api/webhooks/1...."
            asia = "https://discordapp.com/api/webhooks/2...."
            
        [[discord.unfiltered.mixed]]
            eu = "https://discordapp.com/api/webhooks/7...."
            asia = "https://discordapp.com/api/webhooks/8..."   
            
    [discord.unfiltered]
        [[discord.unfiltered.swedish]]
            eu = "https://discordapp.com/api/webhooks/3...."
            asia = "https://discordapp.com/api/webhooks/4...."
         
        [[discord.unfiltered.mixed]]
            eu = "https://discordapp.com/api/webhooks/5...."
            asia = "https://discordapp.com/api/webhooks/6..."   
"""
filtered = True  # 可切换为False
type_filter = "swedish"  # 可切换为"mixed"

collection = configuration.discord.filtered if filtered else configuration.discord.unfiltered

需求

已实现通过filtered布尔值切换到filtered/unfiltered配置分支,需要再根据type_filter的取值,取出对应分类下的地区(eu/asia)和对应的URL值,两个值需要分别作为独立变量使用。
示例预期输出(filtered = True、type_filter = "swedish"时):

eu,  https://discordapp.com/api/webhooks/1....
asia, https://discordapp.com/api/webhooks/2....

最终实现代码

filtered = True  # 可切换为False
type_filter = "swedish"  # 可切换为"mixed"

# 先根据filtered参数确定父级配置分支
collection = configuration.discord.filtered if filtered else configuration.discord.unfiltered

# 用getattr动态获取type_filter对应的配置分支,再遍历取地区和URL
for regions in getattr(collection, type_filter):
    for region, discord_webhook_url in regions.items():
        print(f"Region: {region}, URL {discord_webhook_url}")

逻辑说明

  • 动态属性访问:因为type_filter是字符串类型的变量,无法直接通过collection.属性名的方式访问对应配置,所以使用Python内置的getattr()方法,传入目标对象和属性名字符串,即可动态获取对应属性的配置内容
  • 嵌套遍历:获取到对应类型的配置后,遍历嵌套结构即可分别取出地区、URL两个独立变量,可直接用于后续业务逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 04:45:02