[英]str.format() with lazy dict?
I want to use str.format()
and pass it a custom lazy dictionary. 我想使用
str.format()
并传递一个自定义的懒惰字典。
str.format()
should only access the key in the lazy dict it needs. str.format()
应该只访问它需要的惰性字典中的键。
Is this possible? 这可能吗?
Which interface needs to be implemented by the lazy_dict? lazy_dict需要实现哪个接口?
Update 更新
This is not what I want: 这不是我想要的:
'{0[a]}'.format(d)
I need something like this: 我需要这样的东西:
'{a}'.format(**d)
Need to run on Python2.7 需要在Python2.7上运行
For doing '{a}'.format(**d)
, especially the **d
part, the "lazy" dict is transformed into a regular one. 对于做
'{a}'.format(**d)
,尤其是**d
部分,“懒惰”字典被转换为常规字典。 Here happens the access to all keys, and format()
can't do anything about it. 这里发生了对所有键的访问,而
format()
无法对它做任何事情。
You could craft some proxy objects which are put in place of the elements, and on string access they do the "real" work. 您可以制作一些替代元素的代理对象,并在字符串访问时执行“真正的”工作。
Something like 就像是
class LazyProxy(object):
def __init__(self, prx):
self.prx = prx
def __format__(self, fmtspec):
return format(self.prx(), fmtspec)
def __repr__(self):
return repr(self.prx())
def __str__(self):
return str(self.prx())
You can put these elements into a dict, such as 您可以将这些元素放入dict中,例如
interd = { k, LazyProxy(lambda: lazydict[k]) for i in lazydict.iterkeys()}
I didn't test this, but I think this fulfills your needs. 我没有对此进行测试,但我认为这可以满足您的需求。
After the last edit, it now works with !r
and !s
as well. 在最后一次编辑之后,它现在也适用于
!r
和!s
。
If I understand your question correctly, you want to pass a custom dictionary, that would compute values only when needed. 如果我正确理解您的问题,您希望传递一个自定义词典,该词典仅在需要时计算值。 First, we're looking for implementation of
__getitem__()
: 首先,我们正在寻找
__getitem__()
:
>>> class LazyDict(object):
... def __init__(self, d):
... self.d = d
... def __getitem__(self, k):
... print k # <-- tracks the needed keys
... return self.d[k]
...
>>> d = D({'a': 19, 'b': 20})
>>> '{0[a]}'.format(d)
a
'19'
This shows that only key 'a'
is accessed; 这表明只访问了键
'a'
; 'b'
is not, so you already have your lazy access. 'b'
不是,所以你已经有了懒惰的访问权限。
But also, any object attribute is usable for str.format
this way, and using @property
decorator, you can access function results: 而且,任何对象属性是可用
str.format
这种方式,并使用@property
装饰,您可以访问功能的结果:
class MyObject(object):
def __init__(self):
self.a = 19
self.b = 20
def __getitem__(self, var):
return getattr(self, var)
# this command lets you able to call any attribute of your instance,
# or even the result of a function if it is decorated by @property:
@property
def c(self):
return 21
Example of usage: 用法示例:
>>> m = MyObject()
>>> '{0[c]}'.format(m)
'21'
But note that this also works, making the formating string a little bit specific, but avoid the need for __getitem__()
implementation. 但请注意,这也有效,使格式化字符串有点具体,但避免需要
__getitem__()
实现。
>>> '{0.c}'.format(m)
'21'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.