没有样板的类
attrs的Python项目详细描述
attrs:没有样板的类
attrs是一个python包,它将通过减轻实现对象协议(也称为dunder方法)的繁重工作,使joy恢复writing类的joy。
它的主要目标是帮助您编写concertive和correct软件,而不会降低代码速度。
为此,它提供了一个类装饰器和一种声明性地定义该类上的属性的方法:
>>> importattr>>> @attr.s... classSomeClass(object):... a_number=attr.ib(default=42)... list_of_numbers=attr.ib(factory=list)...... defhard_math(self,another_number):... returnself.a_number+sum(self.list_of_numbers)*another_number>>> sc=SomeClass(1,[1,2,3])>>> scSomeClass(a_number=1, list_of_numbers=[1, 2, 3]) >>> sc.hard_math(3)19 >>> sc==SomeClass(1,[1,2,3])True >>> sc!=SomeClass(2,[3,2,1])True >>> attr.asdict(sc){'a_number': 1, 'list_of_numbers': [1, 2, 3]} >>> SomeClass()SomeClass(a_number=42, list_of_numbers=[]) >>> C=attr.make_class("C",["a","b"])>>> C("foo","bar")C(a='foo', b='bar')
在声明您的属性attrs之后,您将得到:
- 类属性的简明而明确的概述,
- 很好的可读性__repr__,
- 一整套比较方法,
- 初始值设定项,
- 还有更多,
without一次又一次地编写枯燥的样板代码,without运行时性能惩罚。
在python 3.6及更高版本中,您甚至可以通过使用type annotations来放弃对attr.ib()的调用。
这使您能够将实际类与代码中的实际类型一起使用,而不是混淆tuples或confusingly behavingnamedtuples。 这反过来又鼓励您编写small类来完成one thing well。 再也不要因为实现__init__et al是一个痛苦的拖累而违反single responsibility principle。
证明
amber hawkie brown,twisted发布管理器和计算机owl:
Writing a fully-functional class using attrs takes me less time than writing this testimonial.
glyph lefkowitz,在The One Python Library Everyone Needs中,Automat和其他开源软件的创建者:
I’m looking forward to is being able to program in Python-with-attrs everywhere. It exerts a subtle, but positive, design influence in all the codebases I’ve see it used in.
kenneth reitz,digitalocean的Requests作者和开发者倡导者,(on paper no less!):
attrs—classes for humans. I like it.
ukasz langa,facebook的多产cpython核心开发人员和生产工程师:
I’m increasingly digging your attr.ocity. Good job!
项目信息
attrs在MIT许可下发布, 它的文档保存在Read the Docs, 关于GitHub的代码, 以及PyPI上的最新版本。 它在Python2.7、3.4+和Pypy上进行了严格的测试。
我们在wiki中收集有关第三方扩展的信息。 请随意浏览和添加您自己的!
如果你想为attrs捐款,我们会写a little guide让你开始!
发布信息
19.1.0(2019-03-03)
向后不兼容的更改
更改
添加is_callable、deep_iterable和deep_mapping验证器。
- is_callable:验证值是否可调用
- deep_iterable:允许递归到iterable中, 对iterable中的每个成员应用另一个验证器 以及将可选验证器应用于iterable本身。
- deep_mapping:允许递归到映射对象中的项, 对每个项中的密钥和值应用密钥验证器和值验证器。 还将可选验证器应用于映射对象本身。
您可以在attr.validators包中找到它们。 #425
修复了存根文件以防止mypy的disallow_any_generics = True选项引发的错误。 #443
具有init=False的属性现在可以在kw_only=True属性之后跟随。 #450
attrs现在有一个类支持定义异常类。
如果你定义一个clas使用@attr.s(auto_exc=True)并将异常子类化,该类的行为将类似于一个行为良好的异常类,包括一个适当的__str__方法和一个args属性中额外可用的所有属性。 #500
阐明了用于散列的文档,以警告散列对象应该是高度不可变的(在其使用中,即使这不是强制的)。 #503
学分
attrs由Hynek Schlawack编写和维护。
该开发项目得到了Variomedia AG的大力支持。
贡献者的完整列表可以在GitHub’s overview中找到。
它是characteristic的精神继承者,并渴望修复其中一些笨拙和不幸的决定。 两者都是受twisted的FancyEqMixin启发的,但都是使用类装饰器实现的,因为subclassing is bad for you,M'kay?