开发者

using dict vs class __dict__ method to format strings

开发者 https://www.devze.com 2023-03-04 13:44 出处:网络
I have been using dict to format strings s = \'%(name1)s %(name2)s\' d = {} d[\'name1\'] = \'asdf\' d[\'name2\'] = \'whatever\'

I have been using dict to format strings

s = '%(name1)s %(name2)s'
d = {}
d['name1'] = 'asdf'
d['name2'] = 'whatever'
result = s % d

I just realized that I can do this with a class and using the dict method instead:

s = '%(name1)s %(name2)s'
class D : pass
d = D()
d.name1 = 'asdf'
d.name2 = 'whatever'
result = s % d.__dict__

(obviously I do this for bigger strings, and many keys).

Is there any disadvantage to the class approach that I am overlooking? Or is there a bet开发者_开发技巧ter method of doing this string formatting that I am missing?

Thank you.


You can use new-style formatting, which allows getattr and getitem operators in format string:

>>> class X(object):
...     pass
... 
>>> x = X()
>>> x.x = 1
>>> d = {'a':1, 'b':2}
>>> "{0[a]} {0[b]} {1.x}".format(d, x)
'1 2 1'

Regarding disadvantages of your approach - object's __dict__ is limited to whatever attributes and methods particular instance has, so any attribute/method defined at class level will fail:

>>> class X(object):
...     x1 = 1
... 
>>> x = X()
>>> x.x2 = 2
>>> x.__dict__
{'x2': 2}
>>> x.x1
1
>>> x.__dict__['x1']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'x1'

It also does not work with __slots__ and __getattribute__ overrides.


You can also consider creating dict using keyword arguments, e.g.:

d = dict(name1='foo', name2='bar')

Or using format's keyword arguments:

"{name1} baz {name2}".format(name1='foo', name2='bar')
0

精彩评论

暂无评论...
验证码 换一张
取 消