473,562 Members | 3,004 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A decorator syntax not yet mentioned (I think!)

How about the following, which I am almost positive
has not been suggested:
-----
class Klass:
def __init__(self, name):
self.name = name

deco meth0:
staticmethod
def meth0(x):
return x

deco meth1:
classmethod
def meth1(cls):
return cls

deco sayhello:
funcattrs(name= 'GvR', language='pytho n')
log(file='func. log')
def sayhello(self):
print 'hello python world'

-----
1) The decorators clearly apply to a specific method/function,
therefore there is no need to do any stack pushing in memory
until the method/function definition is done.
2) The decorators are "outside" of the method/function they
decorate:
a) which will please those who want the outside location
b) will not be folded within the function
c) folding on the decorators can be done so that the
def is not obfuscated
d) can be located anywhere in the code--but most likely
before the "def ...()"
3) The sequence in which the decorators are applied is just
like code would be--this is certainly intuitive given
that we are writing code.

This approach could also be applied to classes in case
decorators should ever be extended to them:
-----
deco Klass:
doc("This is a class to ...")
class Klass:
:
:
-----

Any comments?

John

Jul 18 '05 #1
41 2827
John Marshall wrote:
How about the following, which I am almost positive
has not been suggested:
-----
class Klass:
def __init__(self, name):
self.name = name

deco meth0:
staticmethod
def meth0(x):
return x

-----
1) The decorators clearly apply to a specific method/function,
therefore there is no need to do any stack pushing in memory
until the method/function definition is done.
Problems with that: duplication (since you now have the name
of the function in two places) and readability (it's harder to
see the "def" because the name you picked is too close to it
in length and appearance).

On the other hand, there's no need to have the function name
there (was anyone complaining about "stack pushing"?), so
maybe just using "decorate" would be okay, or a different
keyword:

class Klass:
# init set

decorate:
staticmethod
def meth0(x):
return x
2) The decorators are "outside" of the method/function they
decorate:
a) which will please those who want the outside location
b) will not be folded within the function
c) folding on the decorators can be done so that the
def is not obfuscated
d) can be located anywhere in the code--but most likely
before the "def ...()"
3) The sequence in which the decorators are applied is just
like code would be--this is certainly intuitive given
that we are writing code. Any comments?


Has potential, I think, with some changes.

I like the following about it:

1) keyword instead of punctuation
2) indentation consistent with rest of Python
3) similarity to try/finally or while/else and friends where
the two clauses are coupled

I wouldn't mind seeing exactly the same idea allowed for
decorators *inside* the function as well, so that we can
experiment for a while and see which, if any, is preferred,
but I doubt that would happen.

-Peter
Jul 18 '05 #2
Peter Hansen wrote:
class Klass:
# init set

decorate:
staticmethod
def meth0(x):
return x


If it counts for anything, +1.

This strikes me personally as a very nice alternative to the
current suggestion.

The idea of paired keywords is sufficiently common in python
to strike me as another positive element.

Using the examples on http://www.python.org/moin/PythonDecorators

You gain something like:
class C(object):

decorate:
staticmethod,
funcattrs(gramm ar="'@' dotted_name [ '(' [arglist] ')' ]",
status="experim ental", author="BDFL")
def longMethodNameF orEffect(longAr gumentOne=None,
longArgumentTwo =42):
"""This method blah, blah.

It supports the following arguments:
- longArgumentOne -- a string giving ...
- longArgumentTwo -- a number giving ...

blah, blah.

"""
raise NotYetImplement ed

And:

decorate:
accepts(int,int )
returns(float)
def bar(low,high):
pass

Which strikes me as pretty good - the fact the method is a static method
is still in your face. The decorate keyword suggests some voodoo
happening you might want to be wary of.

The only downside I can see is that it might not be 100% obvious that it
relates to the following function to newcomers to python.

The other really nice thing about it is it directly suggests that the
following functions will be applied to the function.

Taking a subset of a simple PLY type grammar from, you gain something
like:

class Calc(Parser):
decorate:
tokenrule(r'\d+ ')
def t_NUMBER(self, t):
t.value = int(t.value)
return t

decorate:
tokenrule(r'\n+ ')
def t_newline(self, t):
t.lineno += t.value.count(" \n")

decorate:
grammarrule('st atement : NAME EQUALS expression')
versioninfo("Ad ded in 2.2")
typeinfo(int)
def p_statement_ass ign(self, p):
names[p[1]] = p[3]

decorate:
grammarrule('st atement : expression')
versioninfo("Ad ded in 2.4")
deprecated
typeinfo(None)
def p_statement_exp r(self, p):
print p[1]

decorate:
grammarrule("""
expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression
| expression EXP expression
""")
versioninfo("Ad ded in 2.4")
typeinfo(int)
def p_expression_bi nop(self, p):
p[0] = func[p[2]](p[1],p[3])

decorate:
grammarrule('ex pression : MINUS expression %prec UMINUS')
versioninfo("Ad ded in 1.5")
typeinfo(int)
def p_expression_um inus(self, p):
p[0] = -p[2]

decorate:
grammarrule('ex pression : LPAREN expression RPAREN')
versioninfo("Ad ded in 1.1")
typeinfo(int)
def p_expression_gr oup(self, p):
p[0] = p[2]

In a syntax highlighted editor that also looks *alot* cleaner than
beforehand. IMO, it also looks slightly cleaner than the @version - for
one very, very simple reason - if you have a very big decorator block,
for whatever reason, the "def" stands out clearly so you can skim where
the function starts - even without syntax highlighting.

My initial reaction to @decorators was "ugh!". However I was coming to
accept it as inevitable after reading the various arguments for/against
various syntaxes. *This* syntax strikes me personally as having
distinct advantages - largely for clarity of code, and solves the
"where *DOES* the function start?" question with large decorator
blocks.

My tuppenceworth.. . (I really like this version)
Michael.
--
Mi************@ rd.bbc.co.uk
British Broadcasting Corporation, Research and Development
Kingswood Warren, Surrey KT20 6NP

This message (and any attachments) may contain personal views
which are not the views of the BBC unless specifically stated.
Jul 18 '05 #3
"Peter Hansen" <pe***@engcorp. com> wrote in message
news:Pc******** ************@po wergate.ca...

class Klass:
# init set

decorate:
staticmethod
def meth0(x):
return x

BEAUTIFUL!!! Looks very Pythonic.

This is the first prefix syntax proposal I've seen that looks to address all
of the technical and esthetic objections.

And NO magic punctuation - hooray!

-- Paul
Jul 18 '05 #4
BTW, this syntax is currently listed on the Python MoinMoin as option J2.
http://www.python.org/cgi-bin/moinmoin/PythonDecorators

-- Paul
Jul 18 '05 #5
Michael Sparks wrote:
Peter Hansen wrote:

class Klass:
# init set

decorate:
staticmethod
def meth0(x):
return x


[snip]
My initial reaction to @decorators was "ugh!". However I was coming to
accept it as inevitable after reading the various arguments for/against
various syntaxes. *This* syntax strikes me personally as having
distinct advantages - largely for clarity of code, and solves the
"where *DOES* the function start?" question with large decorator
blocks.


I agree. This seems to fit the absolute requirements I've heard passed
down from GvR, and also avoids all of the things that really made my
teeth grate about the @decorator syntax. It's the first prefix syntax
I've seen that actually *looks* like Python to my eyes.

There's still room for discussion about the specific keyword (I'd be
happy enough with "decorate", and not so fond of "using" or "with", but
a case could easily be made for something else...) and about ordering --
presenting the decorators as a suite

decorate:
d1
d2
def method( ... )
pass

suggests to me an equivalence to

method = d2(d1(method))

which is the reverse of the ordering of @decorators. How significant
the difference is, I can't say...

Jeff Shannon
Technician/Programmer
Credit International

Jul 18 '05 #6
Michael Sparks <mi******@rd.bb c.co.uk> wrote in message news:<cf******* ***@nntp0.reith .bbc.co.uk>...
The only downside I can see is that it might not be 100% obvious that it
relates to the following function to newcomers to python.
This is a downside, but as far as I can tell, it's a downside of all
proposals that place the decorator declaration before the function.
Since it looks like we're stuck with pre-def decorators, I wouldn't
really worry about this issue too much.
In a syntax highlighted editor that also looks *alot* cleaner than
beforehand. IMO, it also looks slightly cleaner than the @version - for
one very, very simple reason - if you have a very big decorator block,
for whatever reason, the "def" stands out clearly so you can skim where
the function starts - even without syntax highlighting.


This is a great point. I definitely agree -- it's much easier to find
the def than even the @ solution. Compare:

@grammarrule('s tatement : expression')
@versioninfo("A dded in 2.4")
@deprecated
@typeinfo(None)
def p_statement_exp r(self, p):
print p[1]

vs.

decorate:
grammarrule('st atement : expression')
versioninfo("Ad ded in 2.4")
deprecated
typeinfo(None)
def p_statement_exp r(self, p):
print p[1]

Of course, you could allow the same thing with '@':

@:
grammarrule('st atement : expression')
versioninfo("Ad ded in 2.4")
deprecated
typeinfo(None)
def p_statement_exp r(self, p):
print p[1]

But this looks really cryptic -- unlike 'decorate', '@' doesn't really
read as anything. You probably know that the '@' "applies" to all the
lines below it, but unless you already know what '@' means, you
probably have no idea how it "applies". The keyword version seems
much clearer on this point.
I know there were complaints before about this sort of indentation,
but I couldn't find them in python-dev and the comments in the wiki
don't discuss this in any detail. Can anyone tell me why this
indentation syntax was dispreferred? Specifically, I'm interested in
why this is so drastically different from the other paired blocks:
if/elif/else, try/except, try/finally, etc. Also, there's a comment
in the wiki that says that there are technical problems with the
grammar if a block *starts* with an optional part. Does this not
apply to the @ case (which also starts a block with an optional part)?

Thanks,

Steve
Jul 18 '05 #7
st************@ gmail.com (Steven Bethard) wrote in message news:<d1******* *************** ****@posting.go ogle.com>...
I know there were complaints before about this sort of indentation,
but I couldn't find them in python-dev and the comments in the wiki
don't discuss this in any detail. Can anyone tell me why this
indentation syntax was dispreferred? Specifically, I'm interested in
why this is so drastically different from the other paired blocks:
if/elif/else, try/except, try/finally, etc.
One thing that's different is that, in all those cases, the second
block has a keyword that can't appear alone. You can't have an except
without a try, or an else without an if, but you could have a def
without a decorate.

For that reason, I suggest it would be a bit more congruent (not
necessarily enough to justify another new keyword) with the rest of
Python to also use a keyword different from def, say ddef.

decorate:
...
ddef function(args):
...

Either is definitely very passable if we must go the before-the-def
route.

Also, there's a comment
in the wiki that says that there are technical problems with the
grammar if a block *starts* with an optional part. Does this not
apply to the @ case (which also starts a block with an optional part)?


It doesn't seem like there would be a problem defining it in, for
example, yacc. def and decorate...def could be two different
statements.
Jul 18 '05 #8
Carl Banks wrote:
st************@ gmail.com (Steven Bethard) wrote in message news:<d1******* *************** ****@posting.go ogle.com>...
I know there were complaints before about this sort of indentation,
but I couldn't find them in python-dev and the comments in the wiki
don't discuss this in any detail. Can anyone tell me why this
indentation syntax was dispreferred? Specifically, I'm interested in
why this is so drastically different from the other paired blocks:
if/elif/else, try/except, try/finally, etc.


One thing that's different is that, in all those cases, the second
block has a keyword that can't appear alone. You can't have an except
without a try, or an else without an if, but you could have a def
without a decorate.


Is this merely a pedantic argument (not sure I use "pedantic" correctly)
or is this an argument based on presumed difficulties in implementing
the idea?

I ask because I'm not sure the issue matters to anyone writing
or reading the code. It certainly wouldn't bother me that
with if/else it's the first part that's required, while with
decorate/def it's the second part.

-Peter
Jul 18 '05 #9
Peter Hansen wrote:


Carl Banks wrote:
st************@ gmail.com (Steven Bethard) wrote in message news:<d1******* *************** ****@posting.go ogle.com>...
I know there were complaints before about this sort of indentation,
but I couldn't find them in python-dev and the comments in the wiki
don't discuss this in any detail. Can anyone tell me why this
indentatio n syntax was dispreferred? Specifically, I'm interested in
why this is so drastically different from the other paired blocks:
if/elif/else, try/except, try/finally, etc.
One thing that's different is that, in all those cases, the second
block has a keyword that can't appear alone. You can't have an except
without a try, or an else without an if, but you could have a def
without a decorate.


Is this merely a pedantic argument (not sure I use "pedantic" correctly)
or is this an argument based on presumed difficulties in implementing
the idea?


Pedantic.

I ask because I'm not sure the issue matters to anyone writing
or reading the code. It certainly wouldn't bother me that
with if/else it's the first part that's required, while with
decorate/def it's the second part.


Well, the only thing is, whenever you see a def statement, you don't
know if it's decorated right away, so you have to expend one or two
extra ergs of energy to look above it and see if it is. (And let's
face it, with the dozens and dozens of decorators that will be applied
to each and every function, it might be a couple screens up. :)

To me, it's totally irrelevant.

I think it would bother some other people, though. I've seen the very
same argument used against a do...while statement. (The do...while
statement didn't bother me either, although ideally I'd prefer do to
replace try in try...finally.)
--
CARL BANKS http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work."
-- Parody of Mr. T from a Robert Smigel Cartoon
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2291
by: Sandy Norton | last post by:
If we are going to be stuck with @decorators for 2.4, then how about using blocks and indentation to elminate repetition and increase readability: Example 1 --------- class Klass: def __init__(self, name):
7
1482
by: John Roth | last post by:
Decorator syntax seems to have been checked into 2.4b2. I'm not going to comment on the syntax other than to say that, when there isn't a real obvious syntax, someone has to make a decision, and this one should work. I was originally against it, on the basis that the only use cases I saw were the elimination of the staticmethod() and...
23
1910
by: C. Barnes | last post by:
I vote for def f(): (body of function) This is backwards compatible (Python <= 2.3 raise SyntaxError), and looks much nicer than @. The only problem is that you can't one-line a decorated function. You can't do that with
24
2035
by: Steven Bethard | last post by:
I think one of the biggest reasons we're having such problems coming to any agreement on decorator syntax is that each proposal makes a number of syntax decisions, not just one. For decorators, I see the following decisions that must be made: 1) Indicator Proposals differ on how some sort of indicator of "decoratorhood" is use. These...
11
1619
by: Ville Vainio | last post by:
It might just be that @decorator might not be all that bad. When you look at code that uses it it's not that ugly after all. A lot of the furor about this is probably because it happened so quicly. The situation might have been different if we had seen a pronouncement a week before, in the vein of "I have chosen this syntax - it will go in...
7
1576
by: Steven Bethard | last post by:
So here's the state of the decorator debate as I see it: *** Location GvR pretty strongly wants decorators before the function: http://mail.python.org/pipermail/python-dev/2004-August/047112.html http://mail.python.org/pipermail/python-dev/2004-August/047279.html
12
1524
by: Steven Bethard | last post by:
The poll, as stated, asked voters to vote for the syntax suggestion they liked the /most/. Some of the conclusions people are trying to draw from it are what syntaxes people liked the /least/. This is probably not the right conclusion to be drawing from the poll that was given. It is, however, the kind of conclusion I think we'd like to...
99
4570
by: Paul McGuire | last post by:
There are a number of messages on the python-dev mail list that indicate that Guido is looking for some concensus to come from this list as to what *one* alternative syntax for decorators we would like him to consider in place of the @ syntax that is currently in 2.4a2. I think special thanks are due to: - Anthony Baxter for his continuing...
28
2365
by: Paul McGuire | last post by:
Well, after 3 days of open polling, the number of additional votes have dropped off pretty dramatically. Here are the results so far: Total voters: 55 (with 3 votes each) Votes for each choice or group of choices: Any J 81 J2 78 Any C 40 C1 29 Any D 9
0
7655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7869
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7627
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6221
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5193
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3623
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2073
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1191
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
903
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.