开发者

'%s' % 'somestring'

Here are a couple of examples taken from django-basic-apps:

# self.title is a unicode string already
def __unicode__(self):
        return u'%s' % self.title

# 'q' is a string
search开发者_如何学编程_term = '%s' % request.GET['q']

What's the point of this string formatting?


It's just a habit of mine. In these cases it's not necessary.


At first glance, it doesn't look sensible, but it does have the benefit of forcing the result to be a string (or unicode string), rather than whatever it might have been from before. Another way to do the same thing might be to call str on the format argument (or unicode).


You're probably better off asking Nathan Borror, the author. It may just be a personal style.

Django does use proxy objects for strings in some cases though, so it may be to force them to "actual" strings. I believe these proxies are for i18n/l10n purposes (don't quote me on that, could also be to avoid db lookups until needed, or a number of other reasons).


Maybe the author is used to strictly typed languages and he misses it in python and this is his way to make python more strictly typed than it is.

Here - to make the types of input/output parameters clear only for the reader because provided all is working as expected it is just useless for the python itself.


Another idea: Maybe this is done with possible future implementations in mind? self.title and request.GET[…] are currently already of the desired type, but implementation details might change in the future, and they might stop being a unicode string or a string.

Now, I would have used str() and unicode(), though…

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜