[Python-Dev] Another approach to decorators.
Martin Zarate
mzarate at uoguelph.ca
Tue Aug 10 18:55:19 CEST 2004
Hello. I've already thrown a few cents into this debate, and have read every
post on it. I've used Ruby, so I love being able to make blocks for whatever
I want - which is why Python's decorator syntax interests me. Its not as
powerful as Ruby blocks, but its a close approach for some things. I can see
the problems are legion. I think the fundamental difficulty is that Python is
line-oriented, and decorators break this - they either make a gigantic line
that the coder remakes as they see fit (very unpython) or a multi-line mess,
which Python does not have for any statements. Second is that Python is an
extremely legible language, and most decorator syntaxes are not.
@ means nothing to an uninformed eye. This violates the most important
feature of Python (imho) which is that it is "runnable pseudocode". A coder
will see what "def" or "class" or "import" means just by looking at it. @ is
meaningless.
I submit that a reserved keyword would fit much better in the @ place.
Second, that comma-based delimiting (like the global statement) would also be
nicer, to avoid line-after-line of decoration.
For example, lets say our keyword is "remake" - a bad word, a better one
should be used, but I'm tired of thinking of one.
remake functor(foo, bar)
remake staticmethod
def baz():
pass
or, alternately,
remake functor(foo,bar), staticmethod
def baz():
pass
but either way, the system doesn't look very Python, as you've a multi-line
statement.
I submit that the most Python solution, that would also be legible (but not
necessarily very pretty) would be to actually make the decorator a bona-fide
block that you nest your class or function into.
remake functor(foo, bar), staticmethod:
def baz():
pass
This concretely shows the relationship of the original define statement to its
wrapper objects. The principle is simple - the remake block will close with
only one object in its immediate namespace, and that object will be wrapped by
each of its argument objects in turn, and place it in its surrounding
namespace with the same name. Thus, more general-purpose oddball approaches
could be used, such as, lambdas or even rewrapping an external object. For
example, in order to import a C-based extension module as a member method in a
class...
class foo(number):
remake instancemethod:
sin = math.sin
bar = foo()
num = bar.sin
or something like that.
other good keywords that could be used instead of remake: wrap, decorate, as,
etc. I'm sure you can all think of something better than @.
More information about the Python-Dev
mailing list