对对象提供可重复的方式,并以100%字节格式序列化它们。

renew的Python项目详细描述


纯python半文本酸洗。
如果仅满足一些限制,则可以存储类
将状态设置为python文件,并将其导入或计算到某个位置
否则或稍后。您甚至可以将其用作数据库,除非
数据量很大。

1分钟-示例:

importrenewclassThatNiceClass(renew.Mold):# manual implementation of __init__ is needed. Constructor_arguments# have to be actual names of this class attributesdef__init__(self,f_a,f_b,*f_c,**f_d):self.f_a,self.f_b,self.f_c,self.f_d=f_a,f_b,f_c,f_dc=ThatNiceClass(1,2,3,4,five=5,six=6)assertrepr(c)=="ThatNiceClass(1, 2, 3, 4, five=5, six=6)"assertc==eval(repr(c))# __eq__ implementedassertrepr(c)==repr(eval(repr(c)))# pure reproduction, instance "survives" evalclassSecondClass(renew.Mold):_cls_namespace="foo_pkg"def__init__(self,one,two="number two",three=None):self.one,self.two,self.three=one,two,threes1=SecondClass(1)s2=SecondClass(3.14159,"non default")s3=SecondClass("Lorem ipsum dolor sit amet, consectetur adipiscing elit")s4=SecondClass(4,three=ThatNiceClass(1,2,3,4,five=5,six=6))d=ThatNiceClass(s1,s2,lorem=s3,im_nesting=s4)assertrepr(d)=="""\
ThatNiceClass(
    foo_pkg.SecondClass(1),
    foo_pkg.SecondClass(3.14159, 'non default'),
    im_nesting=foo_pkg.SecondClass(4, three=ThatNiceClass(1, 2, 3, 4, five=5, six=6)),
    lorem=foo_pkg.SecondClass('Lorem ipsum dolor sit amet, consectetur adipiscing elit'),
)"""

__repr__story-repr(对象)

表示“表示”还是“再现”?
根据python文档__repr__功能有两个
单独进近。从 https://docs.python.org/3/library/functions.html#repr(第3.7.2节)
^{tt4}$ Return a string containing a printable representation of an object.
For many types, this function makes an attempt to return a string
that would yield an object with the same value when passed to eval(),
otherwise the representation is a string enclosed in angle brackets
that contains the name of the type of the object together with
additional information often including the name and address of
the object. A class can control what this function returns for
its instances by defining a ^{tt5}$ method.

一。可重复性报告:

对于多个本机对象,它返回一个可以使用的字符串
复制给定对象,即创建给定对象的副本。
a=[1,3.141559,None,"string"]statement_str=repr(a)assertstatement_str=='[1, 3.141559, None, "string"]'

如果满足以下条件,则可以告诉对象的repr是reproducible

a=[1,3.14159,None,"string"]statement_str=repr(a)assertrepr(eval(statement_str))==statement_str# if the object implements __eq__ this should be also true:asserteval(statement_str)==a

2.描述性报告:

不幸的是,python不提供 框
对于用户定义的类型:
classCar(object):def__init__(self,body_type,engine_power):self.body_type=body_typeself.engine_power=engine_powercar=Car("coupe",124.0)# repr(car) == '<__main__.Car object at 0x7f0ff6313290>'# but using renew:importrenewclassReproducibleCar(renew.Mold):_cls_namespace="bar"def__init__(self,body_type,engine_power):self.body_type=body_typeself.engine_power=engine_powercar2=ReproducibleCar("sedan",110.0)assertrepr(car2)=='bar.ReproducibleCar("sedan", 110.0)'

上面的方法是作为decorator实现的,但是您也可以使用 继承以获得相同的结果。

importrenewclassCar(renew.Mold):_cls_namespace="cars"_cls_dependency="that.things"def__init__(self,body_type,engine_power,fuel,seats,color=None):self.body_type=body_typeself.engine_power=engine_powerself.fuel=fuelself.seats=seatsself.color=colorclassDriver(renew.Mold):_cls_namespace="persons"def__init__(self,first_name,last_name,*cars):self.first_name=first_nameself.last_name=last_nameself.cars=carscar_1=Car("Truck",120.0,"diesel",2)car_2=Car("Van",145.0,"diesel",seats=7,color="silver")car_3=Car("Roadster",210.0,"gasoline",seats=2)driver_1=Driver("Blenda","Klapa",car_1)driver_2=Driver("Trytka","Blotnick",car_2,car_3)assertrepr(driver_1)==".Driver('Blenda', 'Klapa', cars.Car('Truck', 120.0, 'diesel', 2))"assertrepr(driver_2)=="""\
persons.Driver(
    'Trytka',
    'Blotnick',
    cars.Car('Van', 145.0, 'diesel', 7, 'silver'),
    cars.Car('Roadster', 210.0, 'gasoline', 2),
)"""renew.serialize("/tmp/target.py",blenda=driver_1,trytka=driver_2)

创建的文件如下:

#!/usr/bin/env python# -*- coding: utf-8 -*-# This file has been created with renew.# A py-pickling tool: https://pypi.org/project/renew/fromliving.thingsimportpersonsfromthat.thingsimportcarsblenda=persons.Driver('Blenda','Klapa',cars.Car('Truck',120.0,'diesel',2))trytka=persons.Driver('Trytka','Blotnick',cars.Car('Van',145.0,'diesel',7,'silver'),cars.Car('Roadster',210.0,'gasoline',2),)

它是怎么工作的?

注意ReproducibleCar没有显式地实现 __repr__,但是renew.reproducible
decorator对其进行了补充(如果已经定义了decorator,则重写它 之前)。
renew.reproduction检查构造函数的参数规范 修饰类的
并生成一个字符串,该字符串尝试成为调用 语句由
  • namespace,例如您的包名(根据所需的导入 惯例)
  • 给定类名
  • 给定类的属性值,其名称和顺序与 构造函数参数

这是唯一的一个使用限制:

类必须在其属性中存储所有构造函数参数 同样的 名称(如上面的ReproducibleCar定义所示)。

变量参数必须作为list存储在实例中, tuple(不需要转换)、setOrderedDict
(集合通过排序呈现)。关键字参数必须存储在 实例为dictOrderedDict
fromcollectionsimportOrderedDictimportrenewclassThatClass(renew.Mold):def__init__(self,x=1,*others,**kw_args):self.x=xself.others=OrderedDict(others)self.kw_args=kw_argsthat=ThatClass(3.14159,("a","A"),("b","B"),one=1,two=2,many=666)assertrepr(that)=="ThatClass(3.14159, many=666, one=1, two=2)"assertthat.x==3.14159assertthat.others==OrderedDict([("a","A"),("b","B")])assertthat.kw_args==dict(one=1,two=2,many=666)

限制

  • 简单的dict键是“复杂”对象,布局有点难看 如果给定键的repr跨越多行。

  • renew序列化时不交叉引用对象。
    尽管picklemarshal都不交叉引用, renew最有可能做到,但它是
    很难说如何让renew知道对象链的位置和方式 必须相互参照。
  • 对于超能力元编程MacroPyhttps://pypi.org/project/MacroPy/会是更好的选择。

有关功能和使用示例的完整列表,请参阅 测试,尤其是tests/test_renew.py

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java有没有办法在堆栈后保留元素。pop()?   多线程Java:Thread。currentThread()。getName()返回“还没有线程”   java For循环只返回最后一个值   java初始化和比较整数   Java将自定义光标热点设置为图像的中心(.png)   java如何在assertThat中使用带有类型推断的hamcrest nullValue   java Quarkus REST客户端避免空字段的JSON序列化   java使用JFileChooser将语音从文本保存到语音文件   java Android Studio找不到JAR'org。日食jgit4。5.3.201708160445r。罐子   java如何在ElasticSearch中使用带通配符的术语?   java可能的空指针异常安卓   在JavaSwing中使用AwesomeFont中的自定义字体和unicode字符向JButton添加图标?   部署过程中的java持久化单元名称问题WildFly   JavaSpring数据:我无法在数据库中保存关系模型   字符串如何计算文件中单词的长度?JAVA   java Eclipse调试器中变量项旁边的id=xxx是什么   httpclient Java httppost文件打印后上载速度   JAXB对象不实现可序列化的结果是什么?   java Spring JPA数据:自定义通用存储库和服务:未满足PendencyException   java如何从解析类中检索所有值?