Skip to main content

add reference for dict in python using formatted string

Project description

refdict

在Python使用refdict更好地组织数据

使用data['key.key.key.1.2.3']

实现data['key']['key']['key'][1][2][3]的效果

兼容dict/list/tuple/string!

Usage

在字符串值前面加上引用前缀使其变成另一个对象的引用。默认的引用前缀是@。可以在构造函数中传入参数refPrefix来改变引用前缀

[]运算符中使用一个字符串实现refdict内容的链式访问。使用.作为多个key的连接符。可以在构造函数传入参数divider来改变分隔符

data = {
	'player': {
		'name': 'DiscreteTom',
		'items': [
			'@apple',
			'@potion.red'
		],
		'weapon': '@sword',
		'attack': '@player.weapon.attack',
		'me': '@player'
	},
	'apple': 'restore your health by 10%',
	'potion': {
		'red': 'restore your health by 20%',
	},
	'sword': {
		'attack': 123,
		'value': 50
	},
}
rd = refdict(data)
print(rd['player.items.1']) # => restore your health by 20%
print(rd['player.attack']) # => 123
rd['player.items.1'] = 'empty'
print(rd['player.items.1']) # => empty
print(rd['player.items.:.1']) # => empty
rd['player.items.:'] = []
print(rd['player.items']) # => []
print(rd.text('player.me.attack')) # => @player.weapon.attack

Features

  • 能够解析dict/list/tuple/str和其他支持[]运算符的数据类型
    • 如果使用默认的分隔符.,那么dict的key中不能出现.
    • list/tuple/str之外的类型在解析key的时候作为str解析
  • 可以在value中使用.连接属性
    • rd['player.items.1'] = '@potion.red' = 'restore your health by 20%'
  • 链式解析
    • 因为rd['player.weapon'] = '@sword',所以rd['player.attack'] = '@player.weapon.attack' = '@sword.attack' = 123
  • 赋值操作。如果被赋值的对象是引用字符串,则仅解引用,不删除引用目标
    • rd['player.items.1'] = 'empty'解除了原本其指向apple的引用并赋值为empty,但是并没有删除apple
  • 切片取值与赋值。对于list/tuple/str可以使用[:]进行切片
    • rd['player.items.:.1'] = ['@apple', 'empty'][:][1] = ['@apple', 'empty'][1] = 'empty'
  • 使用text函数取字面值。text函数正常计算前n-1个key,然后直接返回最后一个key对应的字面值
    • rd.text('player.me.attack')计算rd['player.me']得到player对象,attack作为最后一个key直接返回字面值@player.weapon.attack

Warnings

使用形如item: @item的递归引用会导致死循环,包括间接递归引用

data = {
	'item': '@item', # => infinite loop!
	'wrapper': {
		'item': '@wrapper.item' # => infinite loop!
	},
	'a': '@b' # => infinite loop!
	'b': '@a' # => infinite loop!
}

Change Log

v2.0.0

改名。还是小写看起来舒服。但是不向前兼容了所以就用2.0.0的版本号好了

v1.0.0

  • 实现[]取值与赋值
  • 实现text函数以获得字面值

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

refdict-2.0.1.tar.gz (3.5 kB view hashes)

Uploaded Source

Built Distribution

refdict-2.0.1-py3-none-any.whl (15.9 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page