473,378 Members | 1,426 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

precedence of [] vs .

I wrote some code to test the precedence of getitem vs getattr; it
shows that getitem binds tighter.

I have been handed some code that relies on the observed behavior.
However, the Nutshell precedence list claims the opposite. Is the
Nutshell wrong or am I missing something or is this a bug?

class a(object):
def __getitem__(self,item):
return str(item)[:-1]

class b(object):
def __getattr__(self,item):
return str(item)[::-1]

Albert = a()
print Albert['abcd']
# prints 'abc'

Barney = b()
print Barney.abc
# print 'cba'

print Barney.Albert['abcd']
# raises TypeError; tries to evaluate 'treblA'['abcd']
# I expected 'cba' based on Nutshell 2d Ed p 50
Aug 14 '08 #1
7 1007
On Thu, Aug 14, 2008 at 6:46 PM, Michael Tobis <mt****@gmail.comwrote:
I wrote some code to test the precedence of getitem vs getattr; it
shows that getitem binds tighter.

I have been handed some code that relies on the observed behavior.
However, the Nutshell precedence list claims the opposite. Is the
Nutshell wrong or am I missing something or is this a bug?

class a(object):
def __getitem__(self,item):
return str(item)[:-1]

class b(object):
def __getattr__(self,item):
return str(item)[::-1]

Albert = a()
print Albert['abcd']
# prints 'abc'

Barney = b()
print Barney.abc
# print 'cba'

print Barney.Albert['abcd']
# raises TypeError; tries to evaluate 'treblA'['abcd']
# I expected 'cba' based on Nutshell 2d Ed p 50
attribute access (foo.bar) binds more tightly than subscripting (foo[bar]).

--
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://techblog.ironfroggy.com/
Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy
Aug 14 '08 #2
On Aug 14, 6:01 pm, "Calvin Spealman" <ironfro...@gmail.comwrote:
>
attribute access (foo.bar) binds more tightly than subscripting (foo[bar]).
That certainly looks right, and in retrospect I wonder that I even
doubted it. But even the official docs seem to me to specify
otherwise:

http://docs.python.org/ref/summary.html

mt

Aug 14 '08 #3


Michael Tobis wrote:
On Aug 14, 6:01 pm, "Calvin Spealman" <ironfro...@gmail.comwrote:
>attribute access (foo.bar) binds more tightly than subscripting (foo[bar]).

That certainly looks right, and in retrospect I wonder that I even
doubted it. But even the official docs seem to me to specify
otherwise:

http://docs.python.org/ref/summary.html
For 3.0, the error message for Barney.Albert)['abcd'] is slightly
different -- TypeError: string indices must be integers -- but the
effect is the same. I submitted
http://bugs.python.org/issue3558

tjr

Aug 15 '08 #4
On Aug 14, 7:17*pm, Michael Tobis <mto...@gmail.comwrote:
On Aug 14, 6:01 pm, "Calvin Spealman" <ironfro...@gmail.comwrote:
attribute access (foo.bar) binds more tightly than subscripting (foo[bar]).

That certainly looks right, and in retrospect I wonder that I even
doubted it. But even the official docs seem to me to specify
otherwise:

http://docs.python.org/ref/summary.html

I think the summary is correct (am not going to bother to double-
check), but there's a subtle point you're missing. Here is a
simplified explanation.
The syntax for subscript operator is:

expression [ expression ]
The syntax for attribute access is:

expression . symbol
The subtle point here is that the symbol that comes after the dot is
NOT an expression, and therefore can't serve as the first expression
in the subscript opreator rules.

The effect of this is that the grouping a.(b[c]) is impossible.
Carl Banks

Aug 15 '08 #5
Calvin Spealman wrote:e
attribute access (foo.bar) binds more tightly than subscripting (foo[bar]).
no, they have the same binding power; here's the relevant part of the
grammar:

trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME

note however that "." only binds to a name, not a full expression (as
Carl noted).

the summary at http://docs.python.org/ref/summary.html is broken; the
source code for that page looks like this:

...
\hline
\lineii{\code{+}, \code{-}}{Addition and subtraction}
\hline
\lineii{\code{*}, \code{/}, \code{\%}}
{Multiplication, division, remainder}
\hline
\lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
\lineii{\code{\~\var{x}}} {Bitwise not}
\hline
\lineii{\code{**}} {Exponentiation}
\hline
\lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
\lineii{\code{\var{x}[\var{index}]}} {Subscription}
\lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
\lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
\hline
...

which indicates that the author intended "." and "[" to appear in the
same box, but got overruled by the Tex->HTML conversion tool.

(if someone has the bandwidth, please submit a documentation bug).

</F>

Aug 15 '08 #6
Carl Banks wrote:
>http://docs.python.org/ref/summary.html

I think the summary is correct (am not going to bother to double-
check), but there's a subtle point you're missing. Here is a
simplified explanation.
the rendered summary is broken; see my other post.

</F>

Aug 15 '08 #7


Fredrik Lundh wrote:
Calvin Spealman wrote:e
>attribute access (foo.bar) binds more tightly than subscripting
(foo[bar]).

no, they have the same binding power; here's the relevant part of the
grammar:

trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME

note however that "." only binds to a name, not a full expression (as
Carl noted).

the summary at http://docs.python.org/ref/summary.html is broken; the
source code for that page looks like this:

...
\hline
\lineii{\code{+}, \code{-}}{Addition and subtraction}
\hline
\lineii{\code{*}, \code{/}, \code{\%}}
{Multiplication, division, remainder}
\hline
\lineii{\code{+\var{x}}, \code{-\var{x}}} {Positive, negative}
\lineii{\code{\~\var{x}}} {Bitwise not}
\hline
\lineii{\code{**}} {Exponentiation}
\hline
\lineii{\code{\var{x}.\var{attribute}}} {Attribute reference}
\lineii{\code{\var{x}[\var{index}]}} {Subscription}
\lineii{\code{\var{x}[\var{index}:\var{index}]}} {Slicing}
\lineii{\code{\var{f}(\var{arguments}...)}} {Function call}
\hline
...

which indicates that the author intended "." and "[" to appear in the
same box, but got overruled by the Tex->HTML conversion tool.

(if someone has the bandwidth, please submit a documentation bug).
Already done: http://bugs.python.org/issue3558

I took the liberty of cutting and pasting your explanation, and added
""x.attribute, x[index], x[index:index], f(arguments...)"
will not fit in the Operator column. I suggest adding
"[Next 4 have same precedence] Trailers"
with the next four lines indented 3 or 4 spaces in each column."

Feel free to add more if you think more is needed.

Terry Jan Reedy

Aug 15 '08 #8

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

Similar topics

10
by: Andrew Koenig | last post by:
It has been pointed out to me that various C++ books disagree about the relative precedence of ?: and the assignment operators. In order to satisfy myself about the matter once and for all, I...
25
by: noe | last post by:
Hello, I'm writing a file system filter driver and I've found in an example this sentence: if (VALID_FAST_IO_DISPATCH_HANDLER( fastIoDispatch, FastIoRead )) { return...
21
by: siliconwafer | last post by:
Hi, In case of following expression: c = a && --b; if a is 0,b is not evaluated and c directly becomes 0. Does this mean that && operator is given a higher precedence over '--'operator? as...
11
by: Rupesh | last post by:
Hello all, See the code .... int i=-3,j=2,k=0,m; m=++i;&&++j||++k; printf ("%d %d %d %d",i,j,k,m); I executed this code on gcc. the o/p i had got is:- -2 3 0 1
25
by: August Karlstrom | last post by:
Hi, Can someone explain the reason for the warning from GCC below: <shell-session> $ cat test.c #include <stdbool.h> bool a, b, c, d;
36
by: Frederick Gotham | last post by:
sizeof has the same precedence as a cast, and they both bind from right to left. The following won't compile for me with gcc: int main(void) { sizeof(double)5; return 0; }
7
by: lovecreatesbea... | last post by:
c-faq, 4.3: The postfix ++ and -- operators essentially have higher precedence than the prefix unary operators. BSD Manual, OPERATOR(7): Operator Associativity...
5
by: junky_fellow | last post by:
Hi, I have a very basic doubt about associativity and precedence of operators. I am not a computer science person and may find it quite weird. Consider an expression 4+5*2
9
by: marko | last post by:
/* code start */ int a = 0; /* expected evaluation and excution order with precedence in mind /* False(3) , True(1), False(2) */ if ( (a=1) == 0 || 0 != 1 && (a =2) == 1) putchar('T');...
7
by: arnuld | last post by:
/* C++ Primer - 4/e * chapter 5 - Expressions * exercises 5.1 and 5.2 */ #include <iostream>
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.