1
0
mirror of https://github.com/django/django.git synced 2025-07-04 01:39:20 +00:00

unicode: Implemented string interpolation for lazy objects.

git-svn-id: http://code.djangoproject.com/svn/django/branches/unicode@5420 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Malcolm Tredinnick 2007-06-03 05:35:06 +00:00
parent bb97eea9ec
commit fa689ae9c6
5 changed files with 30 additions and 3 deletions

View File

@ -32,9 +32,11 @@ def lazy(func, *resultclasses):
self.__dispatch[resultclass] = {} self.__dispatch[resultclass] = {}
for (k, v) in resultclass.__dict__.items(): for (k, v) in resultclass.__dict__.items():
setattr(self, k, self.__promise__(resultclass, k, v)) setattr(self, k, self.__promise__(resultclass, k, v))
if unicode in resultclasses: self._delegate_str = str in resultclasses
self._delegate_unicode = unicode in resultclasses
assert not (self._delegate_str and self._delegate_unicode), "Cannot call lazy() with both str and unicode return types."
if self._delegate_unicode:
self.__unicode__ = self.__unicode_cast self.__unicode__ = self.__unicode_cast
self._delegate_str = str in resultclasses
def __promise__(self, klass, funcname, func): def __promise__(self, klass, funcname, func):
# Builds a wrapper around some magic method and registers that magic # Builds a wrapper around some magic method and registers that magic
@ -62,6 +64,14 @@ def lazy(func, *resultclasses):
else: else:
return Promise.__str__(self) return Promise.__str__(self)
def __mod__(self, rhs):
if self._delegate_str:
return str(self) % rhs
elif self._delegate_unicode:
return unicode(self) % rhs
else:
raise AssertionError('__mod__ not supported for non-string types')
def __wrapper__(*args, **kw): def __wrapper__(*args, **kw):
# Creates the proxy object, instead of the actual value. # Creates the proxy object, instead of the actual value.
return __proxy__(args, kw) return __proxy__(args, kw)

View File

@ -70,7 +70,7 @@ ngettext_lazy = lazy(ngettext, str)
gettext_lazy = lazy(gettext, str) gettext_lazy = lazy(gettext, str)
ungettext_lazy = lazy(ungettext, unicode) ungettext_lazy = lazy(ungettext, unicode)
ugettext_lazy = lazy(ugettext, unicode) ugettext_lazy = lazy(ugettext, unicode)
string_concat = lazy(string_concat, str, unicode) string_concat = lazy(string_concat, unicode)
def activate(language): def activate(language):
return real_activate(language) return real_activate(language)

View File

View File

View File

@ -0,0 +1,17 @@
# coding: utf-8
ur"""
>>> from django.utils.translation import ugettext_lazy, activate, deactivate
>>> s = ugettext_lazy('Add %(name)s')
>>> d = {'name': 'Ringo'}
>>> s % d
u'Add Ringo'
>>> activate('de')
>>> s % d
u'Ringo hinzuf\xfcgen'
>>> activate('pl')
>>> s % d
u'Dodaj Ringo'
>>> deactivate()
"""