python分发实用程序
utils的Python项目详细描述
有时你一遍又一遍地写一个函数;有时你抬头看 在天花板上问“为什么,圭多,为什么这不包括在标准中?” 图书馆?“
好吧,我们也许不能回答这个问题。但我们可以收集这些功能 变成一个集中的地方!
提供的东西
utils被分解成许多功能,以简化 记住某物确切的生活在哪里。
枚举
python没有内置的方法来定义枚举,所以这个模块提供了(我认为)一种非常干净的方法来实现它们。
from utils import enum class Colors(enum.Enum): RED = 0 GREEN = 1 # Defining an Enum class allows you to specify a few # things about the way it's going to behave. class Options: frozen = True # can't change attributes strict = True # can only compare to itself; i.e., Colors.RED == Animals.COW # will raise an exception. # or use the enum factory (no Options, though) ColorsAlso = enum.enum("RED", "GREEN")
一旦定义,使用就很简单:
>>> Colors <class 'blahblah.Colors'> >>> Colors.RED <EnumItem: RED [0]> >>> Colors.RED == 0 True >>> Colors.RED == Colors.RED True >>> Colors.RED = 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "utils/enum.py", line 114, in __setattr__ raise TypeError("can't set attributes on a frozen enum") TypeError: can't set attributes on a frozen enum
数学
目前只有内置的sum的乘法模拟。
听写
交集,差异,筛选,一些特殊的指令…
列表
扁平化和无列表。还有flat_map!
胸部
当前仅提供xor函数。
日期
对于TimePeriod类来说,最酷的是:
>>> from datetime import date # will also work with datetimes >>> time_period = TimePeriod(date(2013, 5, 10), date(2013, 8, 11)) >>> time_period <TimePeriod: 2013-05-10 00:00:00-2013-08-11 23:59:59> >>> date(2013, 6, 12) in time_period True >>> other_time_period = TimePeriod(date(2013, 6, 1), date(2013, 6, 30)) >>> other_time_period in time_period True >>> another_time_period = TimePeriod(date(2013, 8, 1), date(2013, 8, 30)) >>> time_period.overlaps(another_time_period) True >>> TimePeriod.get_containing_period(time_period, another_time_period) <TimePeriod: 2013-05-08 00:00:00-2013-08-30 23:59:59>
等等等等。还有一个DiscontinousTimePeriod类,它 存储时间段的集合。
还有一些常用操作的helper函数,如days_ahead和 days_ago,基本上就是他们在罐头上说的。
对象
提供get_attr,这实际上是一种进行深度getattr链接的方便方法:
>>> get_attr(complicated, 'this.is.a.deep.string', default=None) "the deep string" # or None, if anything in the lookup chain didn't exist
还有一个immutable实用程序,它将包装一个对象并阻止所有属性更改, 默认情况下是递归的。任何在包装对象上设置属性的尝试都将引发AttributeError:
>>> imm = immutable(something) >>> imm <Immutable Something: <Something>> >>> imm.red <Immutable SomethingElse: <SomethingElse: red>> >>> imm.red = SomethingElse('blue') # ... AttributeError: This object has been marked as immutable; you cannot set its attributes. >>> something.red = SomethingElse('blue') >>> imm.red <Immutable SomethingElse: <SomethingElse: blue>>
可以通过指定“recursive”标志来切换递归不变性。