Square bracket and dot notations?

Francesco Bochicchio bieffe62 at gmail.com
Sat Jun 11 06:46:02 EDT 2011


On 11 Giu, 11:41, Asen Bozhilov <asen.bozhi... at gmail.com> wrote:
> Hi all,
> I am beginner in Python. What is interesting for me is that Python
> interpreter treats in different way dot and square bracket notations.
> I am coming from JavaScript where both notations lead prototype chain
> lookup.
>
> In Python it seems square bracket and dot notations lead lookup in
> different "store".
>
> Simple example with dict object:
>
> d = {"key" : "value"}
>
> print d["key"] #value
>
> print d.key #AttributeError
>
> I found an implementation of dict which uses both notations for its
> keys lookup, which I think is stupid idea when obviously both
> notations lead different lookup. It will confuse me as a reader of the
> code.
>
> Anyway, I would like to know more about the lookup for key of dict and
> lookup for property of any object with dot notation. Any materials and
> explanations are highly appreciated.

Since python is not javascript ( duh :-), [] and . notations are used
for different purposes and, although
they share some commonalities as I try to show later in this post,
they should not be intermixed without
a very good reeason ( and "it's cool" is not a good reason IMO).

Broadly speaking, square brackets are used to access element in array,
dict, tuples and sequences.
The dot nootation is used to get the attributes and methods of
instances.

User classes - that is the ones you define with the class statement -
can implement support for the squared bracket and
dot notations:
-  the expression myinstance[index] is sort of translated into  of
myinstance.__getitem__(index)
-   the expression myinstance.myattribute is sort of translated of
myinstance.__getattr__("myattribute")

Classes also exposes a __dict__ attributes that allows to access to
instance attributes and methods using dictionary
semantics. That is, myistance.__dict__["myattribute"]  should give the
same result as  myinstance.myattribute.
I believe this is because in the beginning class instances actually
had a dictionary storing the instance attributes.
Nowadays it is more complex than that, I think,  but the interface is
kept to allow dynamic access to instance contents,
although the reccomended way to do it this is getattr(myinstance,
"myattribute"). Of course it is only useful to use __dict__
or getattr when the parameter is not a constant string but a variable
referring to a string computed at run time  (  this is
what I mean for 'dynamic access' ).

HTH.


Ciao
----
FB




More information about the Python-list mailing list