Skip to main content

yaml-config-loader

轻量级 Python 配置加载工具包,提供类似 Spring Boot 的配置管理能力。

功能特性

  • YAML 配置加载:自动递归查找 application.yml,全局缓存配置
  • @configuration_properties:类似 Spring Boot 的配置属性绑定,支持嵌套 dataclass 自动转换
  • @Value:类似 Spring Boot 的 @Value("${...}"),单个配置值注入,支持嵌套路径和默认值
  • aliases 别名映射:yml 中的数字 key(如 "1002")、关键字等映射到合法的 Python 属性名
  • 自动 kebab-case → snake_case 转换:yml 中的 api-key 自动映射到 Python 的 api_key,无需手动配置
  • @component 单例容器:轻量级 IoC 容器,自动注册和获取 Bean
  • DotDict 点访问字典:支持 config.user.name 方式访问嵌套字典
  • 零配置:开箱即用,无需复杂设置

安装

pip install yaml-config-loader

v1.1.0 包名变更说明:import 包名已从 config_loader 更名为 yaml_config_loader,与 PyPI 包名保持一致,这样 PyCharm 等 IDE 能自动识别并提示"安装软件包"。

旧代码 from config_loader import ... 仍然可用(兼容别名包),但推荐新代码使用 from yaml_config_loader import ...。

更新日志

v1.2.0(最新)

新增功能:

  1. @Value 单值注入:类似 Spring Boot @Value("${...}"),支持两种用法
    • Annotated + @value_config(推荐,保留类型注解)
    • 描述符方式(简洁,无需类型注解)
  2. aliases 别名映射:解决 yml 中数字 key(如 "1002")、Python 关键字(如 class)无法作为属性名的问题
  3. 自动 kebab-case → snake_case 转换:yml 中的 api-key 自动映射到 Python 的 api_key,嵌套对象也自动转换,无需手动写 aliases

优化:

  • get_bean() 支持直接传类对象 get_bean(MyService),不再只能传类名字符串
  • DotDict 构造函数递归转换嵌套 dict,DotDict(config) 直接支持点访问

v1.1.0

  • import 包名从 config_loader 更名为 yaml_config_loader(与 PyPI 包名一致)
  • 保留 config_loader 兼容别名包,老用户代码无需修改

v1.0.0

  • 初始版本:YAML 配置加载、@configuration_properties、@component、DotDict

快速开始

1. 创建 application.yml

user:
  name: "张三"
  age: 25
  email: "zhangsan@example.com"
  address:
    city: "北京"
    street: "长安街"
  # kebab-case(连字符)自动转换为 snake_case(下划线)
  api-key: "abc123"
  server-timeout: 30
  # 数字 key 需要用 aliases 映射
  "1002": "编号1002的值"

server:
  port: 8080
  host: "localhost"

2. 初始化配置

from yaml_config_loader import init_config

# 一行初始化配置(类似 load_dotenv(find_dotenv()))
# 自动递归查找 application.yml 并加载到全局缓存
init_config()

3. 使用 @configuration_properties 绑定配置

from dataclasses import dataclass
from typing import Optional
from yaml_config_loader import configuration_properties, component, DotDict

@component
@configuration_properties(prefix="user")
@dataclass
class UserConfig:
    name: str = None
    age: int = None
    email: str = None
    address: Optional[DotDict] = None  # 嵌套配置自动转为 DotDict

    def show(self):
        print(f"姓名: {self.name}")
        print(f"年龄: {self.age}")
        print(f"城市: {self.address.city}")  # 点访问嵌套配置

user = UserConfig()
user.show()

4. 嵌套 dataclass 自动转换

from dataclasses import dataclass
from typing import Optional
from yaml_config_loader import configuration_properties

@dataclass
class Address:
    city: str = None
    street: str = None

@configuration_properties(prefix="user")
@dataclass
class UserConfig:
    name: str = None
    address: Optional[Address] = None  # 自动转为 Address 实例

user = UserConfig()
print(user.address.city)  # 北京

5. 自动 kebab-case → snake_case 转换

yml 中的 api-key(连字符)自动映射到 Python 的 api_key(下划线),不需要写 aliases,嵌套对象也自动转换。

yml 配置:

user:
  api-key: "abc123"
  server-timeout: 30
  nested:
    my-name: "嵌套配置"

Python 代码:

from dataclasses import dataclass
from yaml_config_loader import configuration_properties

@configuration_properties(prefix="user")
@dataclass
class UserConfig:
    # yml 中的 api-key → 自动映射到 api_key
    api_key: str = None
    # yml 中的 server-timeout → 自动映射到 server_timeout
    server_timeout: int = None
    # 嵌套对象中的 my-name → 自动映射到 my_name
    nested: dict = None

user = UserConfig()
print(user.api_key)          # abc123
print(user.server_timeout)   # 30
print(user.nested.my_name)   # 嵌套配置

转换规则:

yml 中的 key Python 属性名 是否需要 aliases
api-key api_key ❌ 自动转换
server-timeout server_timeout ❌ 自动转换
my-name my_name ❌ 自动转换
"1002"(纯数字) _1002 / item_1002 ✅ 需要 aliases
"class"(关键字) class_type ✅ 需要 aliases

6. aliases 别名映射

当 yml 中的 key 是纯数字(如 "1002")或 Python 关键字(如 class)时,无法作为 Python 属性名,用 aliases 参数做映射。

yml 配置:

user:
  "1002": "编号1002的值"
  "1003": 1003
  "class": "用户类"

Python 代码:

from dataclasses import dataclass
from yaml_config_loader import configuration_properties

@configuration_properties(
    prefix="user",
    aliases={
        "item_1002": "1002",   # Python 属性名 item_1002 ← yml key "1002"
        "item_1003": "1003",   # Python 属性名 item_1003 ← yml key "1003"
        "class_type": "class",  # Python 属性名 class_type ← yml key "class"
    },
)
@dataclass
class UserConfig:
    item_1002: str = None
    item_1003: int = None
    class_type: str = None

user = UserConfig()
print(user.item_1002)   # 编号1002的值
print(user.item_1003)   # 1003
print(user.class_type)   # 用户类

aliases 格式:

aliases={
    "Python属性名": "yml中的key名",
}

优先级:

  1. aliases 显式映射(优先级最高)
  2. 自动 kebab-case → snake_case 转换
  3. 直接用 yml key

7. 使用 @Value 注入单个配置值

类似 Spring Boot 的 @Value("${...}"),只读取单个配置值,更轻量灵活。

推荐用法(Annotated + @value_config,保留类型注解):

from typing import Annotated
from yaml_config_loader import init_config, Value, value_config

init_config()

@value_config
class AppConfig:
    # 基本用法:读取 user.name
    name: Annotated[str, Value(key="user.name", default="未知用户")] = None

    # 带默认值:配置不存在时返回 18
    age: Annotated[int, Value(key="user.age", default=18)] = None

    # 嵌套路径:支持点分隔,如 user.address.city
    city: Annotated[str, Value(key="user.address.city", default="未知城市")] = None

    # 读取其他前缀的配置
    server_port: Annotated[int, Value(key="server.port", default=8080)] = None

app = AppConfig()
print(app.name)         # 张三
print(app.age)          # 25
print(app.city)         # 北京
print(app.server_port)  # 8080

简洁用法(描述符方式,无需类型注解):

from yaml_config_loader import init_config, Value

init_config()

class AppConfig:
    name = Value("user.name")
    age = Value("user.age", default=18)
    city = Value("user.address.city", default="未知城市")

说明:Python 语法不支持 @Value 直接写在类属性上(@装饰器 只能用于 def 和 class),因此用 Annotated + @value_config 的方式实现等价效果,同时保留类型提示。

@Value 与 @configuration_properties 的区别:

特性 @Value @configuration_properties
适用场景 只需要几个配置值 需要绑定一整组配置
用法 Annotated[str, Value(key="...")] + @value_config 类装饰器 @configuration_properties(prefix="user")
默认值 支持 default=xxx 字段默认值
嵌套路径 支持点分隔 user.address.city 自动绑定嵌套 dataclass
类型注解 ✅ 保留 ✅ 配合 @dataclass
只读 ✅ 禁止直接赋值 ❌ 可修改
kebab-case 自动转换 ❌ 需手动写完整路径 ✅ 自动转换
aliases 支持 ❌ 需手动写完整路径 ✅ 支持

8. 使用单例容器

from yaml_config_loader import component, get_bean

@component
class MyService:
    def hello(self):
        return "Hello, World!"

# 获取单例实例(支持直接传类对象)
service = get_bean(MyService)
print(service.hello())  # Hello, World!

# 也支持传类名字符串
service2 = get_bean("MyService")
print(service is service2)  # True(单例)

9. 直接使用 YAML 加载工具

from yaml_config_loader import load_yaml, get_yaml_config, find_yaml

# 自动查找并加载 application.yml
load_yaml()

# 获取全局配置
config = get_yaml_config()
print(config["user"]["name"])  # 张三

# 查找配置文件路径
path = find_yaml()
print(path)

API 参考

装饰器/类

装饰器/类 说明
@configuration_properties(prefix="xxx", aliases={...}) 绑定 YAML 配置到类属性,支持 aliases 别名映射和自动 kebab-case 转换
@value_config 类装饰器,扫描 Annotated 中的 Value 元数据,自动创建描述符
@component 注册为单例 Bean
Value(key="...", default=xxx) 单个配置值注入描述符(类似 Spring Boot @Value)

函数

函数 说明
init_config(filename="application.yml", verbose=True) 一行初始化配置(查找 + 加载)
load_yaml(path=None) 加载 YAML 配置到全局缓存
find_yaml(filename="application.yml") 递归查找 application.yml 文件路径
get_yaml_config() 获取全局配置字典
get_loaded_yaml_path() 获取已加载的配置文件路径
get_bean(cls_or_name) 获取单例 Bean 实例(支持类对象或类名)
list_beans() 列出所有已注册的 Bean
to_dot_dict(d, kebab_to_snake=False) 将普通字典转为 DotDict,可选 kebab-case 转换

类

类 说明
DotDict 支持点访问的字典,构造时递归转换嵌套 dict
Value 单个配置值注入描述符,支持嵌套路径和默认值,只读

配置文件查找规则

find_yaml() 会按以下顺序递归查找:

  1. 当前脚本所在目录
  2. 当前目录下的常见配置子目录(config/、conf/、resources/ 等)
  3. 定位项目根目录(通过 .git、pyproject.toml 等标记)
  4. 在整个项目范围内递归搜索(自动排除 .venv、__pycache__、.git 等目录)

支持的文件名:application.yml、application.yaml

许可证

MIT License

Metadata

Release files for yaml-config-loader 1.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for yaml-config-loader 1.2.0
File Size Uploaded
yaml_config_loader-1.2.0.tar.gz 18.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for yaml-config-loader 1.2.0
File Interpreter ABI Platform
yaml_config_loader-1.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 36.1 kB

Release files / yaml_config_loader-1.2.0.tar.gz

Download URL yaml_config_loader-1.2.0.tar.gz
Size 18.3 kB
Tags Source
SHA-256 checksum
How to use checksums
56efc5240a67a3d10294cd8727024698141137a26c2b69cc655db6d0e9befd8a
BLAKE2b-256 checksum
How to use checksums
00571c17e0ec928cf268605a2775f6b045dae305ec06dfcd98bfc15e271ae3bb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.7

Release files / yaml_config_loader-1.2.0-py3-none-any.whl

Download URL yaml_config_loader-1.2.0-py3-none-any.whl
Size 17.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6369c70e7f04d537d42c93c708a9bd4b9d3ffa58ea3fe6f99633ae3d7198af10
BLAKE2b-256 checksum
How to use checksums
04ac70812dd6afe6e49b5bfc74976fc14b427f780bb163c381aae29d7f12b64a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.7

Release history Release notifications | RSS feed

1.3.0

2 release files

This release

1.2.0 This release

2 release files

1.1.0

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page