用于定义具有延迟求值的字符串的Python库
lazy-string的Python项目详细描述
用于定义具有延迟求值的字符串的Python库。在
包提供了一个LazyString类。它的构造函数接受一个可调用的(比如函数),当需要字符串的值时将调用该函数。构造函数还允许为该可调用项指定位置参数和关键字参数:
def__init__(self,func:Callable[...,str],*args:Tuple,**kwargs:Mapping)->None:...
每次访问都会重新计算该值。在
安装
可作为PyPI软件包提供:
^{pr2}$使用
与没有参数的函数一起使用:
fromlazy_stringimportLazyStringdefmake_foo()->str:return"foo"s=LazyString(make_foo)
根据需要评估该值:
>>>s+" bar"'foo bar'>>>str(s)'foo'
表示法明确地告诉它是一个LazyString:
>>>sLazyString('foo')
传递标准字符串是安全的,因为它们将按原样返回:
>>>LazyString("foo bar")'foo bar'
支持标准字符串的方法:
>>>s.upper()'FOO'>>>"f"insTrue>>>dir(s)['__add__','__class__','__contains__','__delattr__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__getnewargs__','__gt__','__hash__','__init__','__init_subclass__','__iter__','__le__','__len__','__lt__','__mod__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__rmod__','__rmul__','__setattr__','__sizeof__','__str__','__subclasshook__','capitalize','casefold','center','count','encode','endswith','expandtabs','find','format','format_map','index','isalnum','isalpha','isascii','isdecimal','isdigit','isidentifier','islower','isnumeric','isprintable','isspace','istitle','isupper','join','ljust','lower','lstrip','maketrans','partition','replace','rfind','rindex','rjust','rpartition','rsplit','rstrip','split','splitlines','startswith','strip','swapcase','title','translate','upper','zfill']
为可调用项提供参数:
defmake_foo(arg1,arg2):returnf"foo {arg1}{arg2}"s=LazyString(make_foo,123,arg2=456)
>>>str(s)'foo 123 456'
实施细节
LazyString是从collections.UserString继承的。在
>>>LazyString.__mro__(<class'lazy_string.LazyString'>, <class 'collections.UserString'>,<class'collections.abc.Sequence'>, <class 'collections.abc.Reversible'>,<class'collections.abc.Collection'>, <class 'collections.abc.Sized'>,<class'collections.abc.Iterable'>, <class 'collections.abc.Container'>,<class'object'>)
序列化
酸洗
现成支持:
>>>importpickle>>>s==pickle.loads(pickle.dumps(s))True
到JSON
{tt4}支持使用任何^:4编码}
importjsonimportcollectionsclassJSONEncoder(json.JSONEncoder):defdefault(self,o):ifisinstance(o,collections.UserString):returnstr(o)returnsuper().default(o)
>>>data={'s':s}>>>json.dumps(data,cls=JSONEncoder)'{"s": "foo"}'
- 项目
标签: