将某些数据类字段设置为只读
partial-readonl的Python项目详细描述
部分只读
partial_readonly
提供一个decorator,用于方便地使数据类中的某些字段只读。除了python标准库之外,没有其他依赖项。
用法
快速启动
使用partail_readonly
,通过创建与之相关的属性,我们可以轻松地将dataclass
中的某些字段设置为只读。(注意:我们仍然不能将origin字段设置为只读,因为在调用__init__
时仍需要设置它)
例如,下面的代码
fromdataclassesimportdataclass@dataclassclassData:id:int=0name:str=''@propertydeffull_name(self):returnself.name
可以使用partial_readonly
fromdataclassesimportdataclass@dataclassclassData:id:int=0_name:'str alias=full_name'=''
详细信息
- 通过添加下划线前缀将字段标记为只读
_id: int
表示id
是只读的
- 默认情况下,名为like field的相对属性没有下划线前缀
_id: int
将生成名为id
的属性
- 使用字符串注释并在末尾添加
alias=alias_you_want
,您将拥有一个名为alias_you_want
的属性。_id: 'int alias=security_id
将生成名为security_id
的属性
安装
要安装partial_readonly
,只需使用pip
:
pip install partial_readonly
或者使用easy_install
:
easy_install partial_readonly
深入
- 通过设置getter[并禁止setter]将属性设置为只读
- 使用ast为新属性生成getter
- 滥用注释的想法来自zmitchell/annotation-abuse
为什么部分只读
最新的python为我们提供了数据类,以便以方便的方式创建一些类。
但如果我们不希望所有字段都是只读的,那就不方便了。
要求
- python=3.7
后记
我做这个是为了练习ast和发布。
我认为它工作得很好。
有一些更容易实现。
如果你分享一些关于这个功能的想法,我会很高兴的!
许可证
MIT License
Copyright (c) 2018 book987
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.