跳转到主要内容

Python Utils是一个包含一些方便实用工具的模块,这些工具不包括在标准Python安装中

项目描述

https://github.com/WoLpH/python-utils/actions/workflows/main.yml/badge.svg?branch=master https://coveralls.io/repos/WoLpH/python-utils/badge.svg?branch=master

Python Utils是一组小型Python函数和类,可以缩短并简化常见的模式。它绝对不是一个完整的集合,但它在过去为我提供了很多帮助,我将继续扩展它。

使用Python Utils的一个库是Django Utils。

文档可在以下地址找到:https://python-utils.readthedocs.org/en/latest/

安全联系方式

要报告安全漏洞,请使用Tidelift安全联系方式。Tidelift将协调修复和披露。

安装要求

对于Python 3+版本(即v3.0.0或更高版本),没有要求。对于与Python 2兼容的版本(v2.x.x),需要six包。

安装

可以通过pip(这是推荐的方法)安装此包

pip install python-utils

如果没有pip,也可以使用easy_install

easy_install python-utils

或者从Pypi(https://pypi.python.org/pypi/python-utils)或Github下载最新版本。

请注意,Pypi上的版本使用我的GPG密钥签名(https://pgp.mit.edu/pks/lookup?op=vindex&search=0xE81444E9CE1F695D),可以使用GPG进行验证

gpg --verify python-utils-<version>.tar.gz.asc python-utils-<version>.tar.gz

快速入门

此模块使Python脚本中的常见任务执行变得简单,例如将文本转换为数字,并确保字符串是Unicode或字节格式。

示例

使用装饰器自动将生成器转换为列表、字典或其他集合

>>> @decorators.listify()
... def generate_list():
...     yield 1
...     yield 2
...     yield 3
...
>>> generate_list()
[1, 2, 3]

>>> @listify(collection=dict)
... def dict_generator():
...     yield 'a', 1
...     yield 'b', 2

>>> dict_generator()
{'a': 1, 'b': 2}

重试直到超时

为了轻松重试具有可配置超时的代码块,您可以使用time.timeout_generator

>>> for i in time.timeout_generator(10):
...     try:
...         # Run your code here
...     except Exception as e:
...         # Handle the exception

时间戳、日期和时间的格式化

轻松格式化时间戳和计算时间差

>>> time.format_time('1')
'0:00:01'
>>> time.format_time(1.234)
'0:00:01'
>>> time.format_time(1)
'0:00:01'
>>> time.format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))
'2000-01-02 03:04:05'
>>> time.format_time(datetime.date(2000, 1, 2))
'2000-01-02'
>>> time.format_time(datetime.timedelta(seconds=3661))
'1:01:01'
>>> time.format_time(None)
'--:--:--'

>>> formatters.timesince(now)
'just now'
>>> formatters.timesince(now - datetime.timedelta(seconds=1))
'1 second ago'
>>> formatters.timesince(now - datetime.timedelta(seconds=2))
'2 seconds ago'
>>> formatters.timesince(now - datetime.timedelta(seconds=60))
'1 minute ago'

将测试从驼峰式命名法转换为下划线

>>> camel_to_underscore('SpamEggsAndBacon')
'spam_eggs_and_bacon'

属性设置装饰器。在Django admin中非常有用

一个方便的装饰器,用于使用装饰器设置函数属性

You can use:
>>> @decorators.set_attributes(short_description='Name')
... def upper_case_name(self, obj):
...     return ("%s %s" % (obj.first_name, obj.last_name)).upper()

Instead of:
>>> def upper_case_name(obj):
...     return ("%s %s" % (obj.first_name, obj.last_name)).upper()

>>> upper_case_name.short_description = 'Name'

这对于Django admin非常有用,因为它允许您在单个位置拥有所有元数据。

在范围之间缩放数字

>>> converters.remap(500, old_min=0, old_max=1000, new_min=0, new_max=100)
50

# Or with decimals:
>>> remap(decimal.Decimal('250.0'), 0.0, 1000.0, 0.0, 100.0)
Decimal('25.0')

获取屏幕/窗口/终端的字符大小

>>> terminal.get_terminal_size()
(80, 24)

该方法支持IPython、Jupyter以及常规shell,使用blessings和其他模块,具体取决于可用性。

从几乎所有字符串中提取数字

>>> converters.to_int('spam15eggs')
15
>>> converters.to_int('spam')
0
>>> number = converters.to_int('spam', default=1)
1

以编程方式全局导入包中的所有模块

要编程方式进行全局导入,您可以使用import_global函数。这实际上模拟了from … import *

from python_utils.import_ import import_global

# The following is  the equivalent of `from some_module import *`
import_global('some_module')

为类自动命名日志记录器

或向您的类添加正确命名的日志记录器,以便轻松访问

class MyClass(Logged):
    def __init__(self):
        Logged.__init__(self)

my_class = MyClass()

# Accessing the logging method:
my_class.error('error')

# With formatting:
my_class.error('The logger supports %(formatting)s',
               formatting='named parameters')

# Or to access the actual log function (overwriting the log formatting can
# be done n the log method)
import logging
my_class.log(logging.ERROR, 'log')

或者也支持loguru。它基本上是日志模块的替代品,配置起来更方便

首先安装额外的loguru包

pip install 'python-utils[loguru]'
class MyClass(Logurud):
    ...

现在您可以使用Logurud类来使函数如self.info()可用。这种方法的优点是您可以为特定的loguru实例(即self.logger)添加额外的上下文或选项

方便的类型别名和一些常用类型

# For type hinting scopes such as locals/globals/vars
Scope = Dict[str, Any]
OptionalScope = O[Scope]

# Note that Number is only useful for extra clarity since float
# will work for both int and float in practice.
Number = U[int, float]
DecimalNumber = U[Number, decimal.Decimal]

# To accept an exception or list of exceptions
ExceptionType = Type[Exception]
ExceptionsType = U[Tuple[ExceptionType, ...], ExceptionType]

# Matching string/bytes types:
StringTypes = U[str, bytes]

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

python_utils-3.9.0.tar.gz (35.4 kB 查看哈希值)

上传时间

构建分发

python_utils-3.9.0-py2.py3-none-any.whl (32.1 kB 查看哈希值)

上传于 Python 2 Python 3

支持者