[Python-Dev] New syntax for 'dynamic' attribute access

Scott Dial scott+python-dev at scottdial.com
Tue Feb 13 01:07:11 CET 2007


Brett Cannon wrote:
> On 2/12/07, Guido van Rossum <guido at python.org> wrote:
>> I recommend that you do some experiments with the readability of the
>> .[...] notation, e.g. write a program that randomly generates x.[foo]
>> and x[foo], and see how fast you can spot the difference. I bet that
>> you won't have any trouble.
>>
> 
> OK, so real-world examples.  First, ``foo.(name)``, from urllib.py::
> 
[snip]
> 
> Neither version jumps out at me strongly, although between the two the
> ``.[]`` version shows up the best.  But that might also be because of
> the lower noise when used in a call.
> 
> -Brett

After seeing a real-world example of the notation, I'm not a fan. Like 
Brett, of the two I find ".[]" to be the most readable. I do in fact 
immediately associate an identifier next to "()" with being a function 
call, regardless of the dot. The "[]" immediately associates me with a 
type of dereferencing action which is more appropriate for the context.

The danger here is that "foo.bar" and "baz.(bar)" use "bar" in 
drastically different ways and it is not made obvious enough. 
"baz.[bar]" gets you closer because we are used to seeing "bar" as a 
variable containing a key (as opposed to "foo.bar" where 'bar' is in 
fact the key).

At the risk of needing flame retardant, I would propose the use of 
something more visually jarring. The first thing that came to mind was 
something like "foo@[bar]". The only usage of the @ symbol I can recall 
is in Ruby where it is used instead of "self." for attribute access, 
which is in the right ballpark for what we mean here and the brackets 
differentiate it still.

To borrow the urllib2.py example:

         if attr[:12] == '_Request__r_':
             name = attr[12:]
             if hasattr(Request, 'get_' + name):
                 self@['get_' + name]()
                 return self@[attr]
         raise AttributeError, attr

-Scott

-- 
Scott Dial
scott at scottdial.com
scodial at cs.indiana.edu


More information about the Python-Dev mailing list