Я, возможно, сомневаюсь, что это хороший вариант использования декораторов, но здесь:
import string
SelfClosing = object()
def escapeAttr(attr):
# WARNING: example only, security not guaranteed for any of these functions
return attr.replace('"', '\\"')
def tag(name, content='', **attributes):
# prepare attributes
for attr,value in attributes.items():
assert all(c.isalnum() for c in attr) # probably want to check xml spec
attrString = ' '.join('{}="{}"'.format(k,escapeAttr(v)) for k,v in attributes.items())
if not content==SelfClosing:
return '<{name} {attrs}>{content}</{name}>'.format(
name = name,
attrs = attrString,
content = content
)
else: # self-closing tag
return '<{name} {attrs}/>'
Пример:
def makeBoldWrapper(**attributes):
def wrapWithBold(origFunc):
def composed(*args, **kw):
result = origFunc(*args, **kw)
postprocessed = tag('b', content=result, **attributes)
return postprocessed
return composed
return wrapWithBold
Демо:
@makeBoldWrapper(attr1='1', attr2='2')
def helloWorld(text):
return text
>>> print( helloWorld('Hello, world!') )
<b attr2="2" attr1="1">Hello, world!</b>
Распространенное заблуждение декораторов состоит в том, что параметры (attr1=...)
являются параметрами декоратора @myDecorator
; Это не относится к делу. Скорее результат вызова функции myDecoratorFactory(attr1=...)
вычисляется как someresult
и становится анонимным декоратором @someresult
. Следовательно, «декораторы с аргументами» на самом деле являются фабриками декораторов, которым необходимо возвращать декоратор в качестве значения.
person
ninjagecko
schedule
19.07.2013