跳转到主要内容

使__repr__、__str__和__unicode__方法文明化

项目描述

https://travis-ci.org/wolever/autorepr.svg?branch=master

现在支持Python 3!

概述

Python使得类易于创建,但__repr__方法比较难。你再次忘记引用self了吗?可能吧。你认为“这个类很简单,不需要repr”?毫无疑问。上周生产系统因你的__str__返回了unicode而崩溃了三次吗?...不?可能这只是我个人的经历。

autorepr使你能够轻松地在一行中构建富有表现力、安全且正确的__repr__、__str__、__unicode__和__bytes__方法。

使用autorepr,你将得到你想要的repr,无需担心繁琐的部分(如编码和解码),让你可以专注于你的项目。

>>> from autorepr import autorepr, autotext
>>> class Person(object):
...     name = u"Alex ☃"
...     height = 123.456
...
...     __repr__ = autorepr(["name", "height:0.1f"])
...     __str__, __unicode__ = autotext("{self.name} ({self.height:0.0f} cm)")
...
>>> p = Person()
>>> repr(p)
"<__main__.Person name=u'Alex \\u2603' height=123.5 at 0x...>"
>>> unicode(p)
u'Alex \u2603 (123 cm)'
>>> str(p)
'Alex \xe2\x98\x83 (123 cm)'

安装

$ pip install autorepr

用法

autorepr提供了两个主要功能

  • autorepr,通过传递一个str.format样式的字符串或应包含在name=value列表中的属性列表,构建一个Python风格的__repr__字符串

    autorepr(["name", "height:0.1f"]) -->
        "<pkg.Person name=u'Alex \u2603' height=123.5 at 0x...>"
    autorepr("{self.id} name={self.name!r}") -->
        "<pkg.Person 123 name=u'Alex \u2603' at 0x...>"
  • autotext,使用autostr和autounicode以Python 2 + 3兼容的方式创建__str__和__unicode__方法

    __str__, __unicode__ = autotext("{self.name} ({self.height!d} cm)") -->
        str: 'Alex \xe2\x98\x83 (123cm)'
        unicode: u'Alex \u2603 (123cm)'

包含三个二级功能 - autostrautounicodeautobytes - 分别构建 __str____unicode____bytes__ 函数。这些函数将尽力避免 Unicode 编码/解码错误,并通常能够正确处理输入,即使输入可能并不合理。

注意:此处显示的示例是 Python 2,但在 Python 3 下同样适用。

>>> from autorepr import autorepr, autotext, autostr, autounicode
>>> class Person(object):
...     name = u"Alex ☃"
...     height = 123.456
...
...     __repr__ = autorepr(["name", "height:0.1f"])
...     __str__, __unicode__ = autotext("{self.name} ({self.height:0.0f} cm)")
...
>>> p = Person()
>>> repr(p)
"<__main__.Person name=u'Alex \\u2603' height=123.5 at 0x...>"
>>> unicode(p)
u'Alex \u2603 (123 cm)'
>>> str(p)
'Alex \xe2\x98\x83 (123 cm)'

注意 autostrautorepr(在此通过 autotext 调用)在转换为/从 Unicode(解码/编码为 UTF-8)方面非常智能。

>>> p.name = u"unicode: ☃"
>>> unicode(p)
u'unicode: \u2603 (123 cm)'
>>> str(p)
'unicode: \xe2\x98\x83 (123 cm)'
>>> p.name = 'utf-8 bytes: \xe2\x98\x83'
>>> unicode(p)
u'utf-8 bytes: \u2603 (123 cm)'
>>> str(p)
'utf-8 bytes: \xe2\x98\x83 (123 cm)'

注意:如果 autostrautorepr 遇到无效的 UTF-8(例如,如果要求 autounicode 将二进制数据转换为 Unicode),则不会崩溃,但结果是不确定的,可能不符合预期。

可以通过 kwargs 传递额外的属性,这些属性将作为参数与实例一起调用。

>>> name_with_len = autostr("{self.name} length={len}",
...                         len=lambda self: len(self.name))
...
>>> p.name = 'Alex'
>>> name_with_len(p)
'Alex length=4'

这同样适用于 autorepr 的列表模式。

>>> repr_with_len = autorepr(["name", "len"],
...                          len=lambda self: len(self.name))
...
>>> repr_with_len(p)
"<__main__.Person name='Alex' len=4 at 0x...>"

如果将常规格式字符串传递给 autorepr,则将使用该字符串而不是生成的字符串。

>>> repr_with_str = autorepr("{self.name!r}")
>>> repr_with_str(p)
"<__main__.Person 'Alex' at 0x...>"

当然,如果您不希望您的 __repr__ 被包裹在 <ClassName ...> 中,您可以使用 autostr

>>> repr_with_autostr = autostr("Person({self.name!r})")
>>> repr_with_autostr(p)
"Person('Alex')"

如果默认的 !r 不理想(例如,截断浮点数),则也可以将格式规范传递给 autorepr

>>> with_fmt_spec = autorepr(["duration:0.1f", "addr:x", "type!s"],
...                          duration=lambda x: 123.456,
...                          addr=lambda x: 0xabc123,
...                          type=lambda x: "foo")
>>> with_fmt_spec(None)
'<....NoneType duration=123.5 addr=abc123 type=foo at 0x...>'

项目详情


下载文件

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

源分布

autorepr-0.3.0.tar.gz (8.7 kB 查看哈希值)

上传时间

构建分布

autorepr-0.3.0-py2.py3-none-any.whl (8.6 kB 查看哈希值)

上传时间 Python 2 Python 3

autorepr-0.3.0-py2-none-any.whl (8.6 kB 查看哈希值)

上传时间 Python 2

支持

AWSAWS云计算和安全赞助商DatadogDatadog监控FastlyFastlyCDNGoogleGoogle下载分析MicrosoftMicrosoftPSF赞助商PingdomPingdom监控SentrySentry错误日志StatusPageStatusPage状态页面