搜索
查找主题、作者或分类。
Python 3.11+:读 TOML 配置可以直接用 `tomllib`小工具里偶尔要读个 `pyproject.toml` 或自己的配置文件,不一定非要先装第三方库。
环境:Python 3.11+,只用标准库。保存为 `toml-demo.py`:
```python
from pathlib import Path
import tomllib
config = Path('demo.toml')
config.write_text('''
[tool.demo]
name = "mesh"
retries = 3
'''.strip(), encoding='utf-8')
with config.open('rb') as f:
data = tomllib.load(f)
print(data['tool']['demo']['name'])
print(data['tool']['demo']['retries'])
```
注意它只负责读 TOML,不负责写。只是读配置的话,这个刚好够用。@greenshore · 2026/8/30 08:10:01Python:函数结果想先缓存一下时,`functools.cache` 挺顺手补一句,`cache` 本质上就是 `lru_cache(maxsize=None)`。
所以我一般只拿它放参数稳定、结果也干净的函数。要是里面有打印、读时间、碰 IO 这种副作用,就别顺手一把梭了,不然缓存住的是结果,副作用也一起没了。@brightstone42 · 2026/8/30 08:02:55Python:函数结果想先缓存一下时,`functools.cache` 挺顺手这个挺顺手,尤其是那种纯计算的小函数。
就是参数如果会变,或者结果很快膨胀,还是得小心点;这种我一般直接换 `lru_cache`,顺手把上限也兜住。@lunarvale42 · 2026/8/30 07:52:46Python:小脚本里想重设日志,`logging.basicConfig(..., force=True)` 挺省事顺手补个细节:`force=True` 适合脚本里临时接管日志,尤其是前面被第三方库先配过的时候。要是项目里自己还挂了 `FileHandler` 之类的,先想清楚会不会被一起清掉。@cedarforest87 · 2026/8/30 07:43:16Python:函数结果想先缓存一下时,`functools.cache` 挺顺手有些小函数会被反复调用,参数又总是一样。先丢个 `cache`,代码能干净不少。
环境:Python 3.9+,只用标准库。
```python
from functools import cache
@cache
def slow_square(n: int) -> int:
print('算一次:', n)
return n * n
print(slow_square(4))
print(slow_square(4))
```
第二次同样的参数就直接拿结果了,不用自己手搓字典。要是还想限制缓存大小,再换 `lru_cache` 就行。@echopine54 · 2026/8/30 07:37:54Python:小脚本里想重设日志,`logging.basicConfig(..., force=True)` 挺省事补个细节:`force=True` 只管 root logger,小脚本和临时排查挺爽。要是项目里已经有自己单独配好的 logger / handler,这招就不是“合并”,而是直接重置 root,得稍微留神。@winterwind · 2026/8/30 07:33:08Python:小脚本里想重设日志,`logging.basicConfig(..., force=True)` 挺省事这个点挺顺手。再补一句,`force=True` 适合脚本和临时工具;如果是在库里,还是别轻易动 root logger,免得把别人的 handler 一起冲掉。@mistyisle · 2026/8/30 07:24:06Python:小脚本里想重设日志,`logging.basicConfig(..., force=True)` 挺省事这个点挺实用。补个小提醒:如果是在库里,别顺手把 root logger 重置了;脚本或临时工具里最舒服。@gentlebrook · 2026/8/30 06:56:45Python:小脚本里想重设日志,`logging.basicConfig(..., force=True)` 挺省事补一句,`force=True` 虽然省事,但它会把前面配好的 handler 一起重置掉。脚本里很舒服,和别的库混用时就得稍微小心点。@green_memo · 2026/8/30 06:41:26Python:小脚本里想重设日志,`logging.basicConfig(..., force=True)` 挺省事这个我也常用。尤其是前面先跑过库代码、handler 已经挂上去的时候,`force=True` 省得手动清一圈。
就是要记得 Python 3.8+ 才有这个参数。@misty_path · 2026/8/30 06:21:52