A dict like variable manager, listen for variable changes.
Project description
VarMan
一个辅助监听变量赋值变化的类,基本用法类似dict类型
应用场景示例
- webapp中开关量的前后台同步,前台需要显示开关状态并且可以控制开关,后台亦然。
- 需要监听变量改变并回调相应方法的情形
使用方法
pip install varman
import varman
var = varman.VarMan()
获取改变值的变量名
var.a = 1
print(var.POPMODIFY(tag = 'tag1'))
var.a = 1
print(var.POPMODIFY(tag = 'tag1'))
var.a = 2
print(var.POPMODIFY(tag = 'tag1'))
var.b = 3
print(var.POPMODIFY(tag = 'tag1'))
print(var.POPMODIFY())
{'a'}
set()
{'a'}
{'b'}
{'a', 'b'}
设置回调函数
# 对应变量“c”的回调函数
@var.ONMODIFY('c')
def fun(pre, nxt):
print(f'pre c:{pre}, next c:{nxt}')
var.c = 1
pre c:None, next c:1
var['c'] = 4
pre c:1, next c:4
# var中任意变量改变时回调
@var.ONMODIFYANY
def func(varname, pre, nxt):
print(f'var:{varname}; pre: {pre}, next:{nxt}')
var.c = 1
pre c:4, next c:1
var:c; pre: 4, next:1
var.a = 5
var:a; pre: 2, next:5
var.dd = []
var:dd; pre: None, next:[]
# 只能监听基本变量,或变量的id改变,无法监听list、dict等类型的内部更改
var.dd.append(1)
主动触发(2024年1月14日)
var.CALLONMODIFY('c') # 强制调用变量c的回调函数
# 移除监听器
var.REMOVELISTENER('c')
var.c = 8
var:c; pre: 1, next:8
# 移除对任意变量的监听器
var.REMOVEANYLISTENER()
var.c = 10
作为iter类型使用(类似dict)
for key in var:
print(f'{key}:{var[key]}')
a:5
b:3
c:10
dd:[1]
# 带前缀“_”的变量将隐式调用,不会自动监听赋值状态,也不会被迭代
# 不允许“__”前缀
var._d = 5
for key in var:
print(f'{key}:{var[key]}')
a:5
b:3
c:10
dd:[1]
print(var._d)
5
def fun2(**params):
print(params)
fun2(**var)
{'a': 5, 'b': 3, 'c': 10, 'dd': [1]}
# 实例化的同时添加变量
var2 = varman.VarMan(d = 8, e=10)
print(var2)
{'d': 8, 'e': 10}
var2
VarMan({'d': 8, 'e': 10})
todo?
- 删除变量
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
varman-0.1.4.tar.gz
(4.4 kB
view details)
Built Distribution
File details
Details for the file varman-0.1.4.tar.gz
.
File metadata
- Download URL: varman-0.1.4.tar.gz
- Upload date:
- Size: 4.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.10.13
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3d5df5f29623c4018ad71322f021db10098209bce98fd39d1e907fe9cbec2331 |
|
MD5 | 6a1209dd781c4679b3c29146e7233f3a |
|
BLAKE2b-256 | 9ef14aca5c0248b0e62a456f117b0e7bb6844d06db30651884a5134181fcf5ce |
File details
Details for the file varman-0.1.4-py3-none-any.whl
.
File metadata
- Download URL: varman-0.1.4-py3-none-any.whl
- Upload date:
- Size: 4.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.10.13
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9609481136f1ceb3d18d8225c1c6f06098cde6deda50e828e8420612bab70fc6 |
|
MD5 | 7c6fed8564193de4abaee9435634aaf0 |
|
BLAKE2b-256 | c221dbed65dd4ae428c5d6811476a120ab37b03892689992c5624bf243ee5d9c |