Quora的核心实用程序库
qcore-nocython的Python项目详细描述
qcore是Quora使用的公共实用程序函数库。它习惯于 抽象出其他Quora库(如asynq)的通用功能。
下面讨论它的组件模块。查看代码中的docstrings 更多细节。
qcore.asserts
当一个普通的python断言失败时,它只表示有一个失败, 不是导致断言失败的错误值。本模块 提供自动生成更好错误的丰富断言帮助程序 信息。例如:
>>>fromqcore.assertsimportassert_eq>>>assert5==2*2Traceback(mostrecentcalllast):File"<stdin>",line1,in<module>AssertionError>>>assert_eq(5,2*2)Traceback(mostrecentcalllast):File"<stdin>",line1,in<module>File"qcore/asserts.py",line82,inassert_eqassertexpected==actual,_assert_fail_message(message,expected,actual,'!=',extra)AssertionError:5!=4
标准库的unittest包提供了类似的方法, 但是它们与TestCase类绑定,而不是独立的 功能。
qcore.caching
这提供了缓存数据的帮助程序。一些示例包括:
fromqcore.cachingimportcached_per_instance,lazy_constant@lazy_constantdefsome_function():# this will only be executed the first time some_function() is called;# afterwards it will be cachedreturnexpensive_computation()classSomeClass(object):@cached_per_instance()defsome_method(self,a,b):# for any instance of SomeClass, this will only be executed oncereturnexpensive_computation(a,b)
qcore.debug
这个模块提供了一些对调试python有用的帮助程序。尤其是 包括@qcore.debug.trace()decorator,它可用于跟踪 每次调用函数时。
qcore.decorators
此模块为支持 透明地修饰函数、方法、类方法和静态方法 同时还提供了添加其他自定义属性的选项。为了 例如,它可以用来提供一个缓存修饰符,该修饰符添加一个.dirty 修饰函数的属性以脏化其缓存:
fromqcore.decoratorsimportDecoratorBase,DecoratorBinder,decorateclassCacheDecoratorBinder(DecoratorBinder):defdirty(self,*args):ifself.instanceisNone:returnself.decorator.dirty(*args)else:returnself.decorator.dirty(self.instance,*args)classCacheDecorator(DecoratorBase):binder_cls=CacheDecoratorBinderdef__init__(self,*args):super(CacheDecorator,self).__init__(*args)self._cache={}defdirty(self,*args):try:delself._cache[args]exceptKeyError:passdef__call__(self,*args):try:returnself._cache[args]exceptKeyError:value=self.fn(*args)self._cache[args]=valuereturnvaluecached=decorate(CacheDecorator)
qcore.enum
这个模块提供了一个定义枚举的抽象。可以定义枚举 如下所示:
fromqcore.enumimportEnumclassColor(Enum):red=1green=2blue=3
qcore.错误
此模块提供了一些常用的异常类和帮助程序 从另一个地方重新发布异常。
qcore.events
这为注册事件和运行回调提供了一个抽象。 示例用法:
>>>fromqcore.eventsimportEventHook>>>event=EventHook()>>>defcallback():...print('callback called')...>>>event.subscribe(callback)>>>event.trigger()callbackcalled
qcore.helpers
这提供了许多小的助手函数。
qcore.inspectable_类
这提供了一个基类,该基类自动提供散列、等式 检查和可读的repr()结果。示例用法:
>>>fromqcore.inspectable_classimportInspectableClass>>>classPair(InspectableClass):...def__init__(self,a,b):...self.a=a...self.b=b...>>>Pair(1,2)Pair(a=1,b=2)>>>Pair(1,2)==Pair(1,2)True
qcore.检查
这提供了类似于标准inspect模块的功能。在…之间 其他的,它包括get_original_fn函数,它提取 来自qcore.decorators-修饰对象的基础函数。
qcore.microtime
这包括处理时间的助手,表示为整数 从Unix时代开始的微秒。
qcore.测试
这提供了在单元测试中使用的帮助程序。其中,它提供了 Anything对象,与任何其他python对象进行比较。