Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Square bracket and dot notations?

52 views
Skip to first unread message

Asen Bozhilov

unread,
Jun 11, 2011, 5:41:36 AM6/11/11
to
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.

Andrew Berg

unread,
Jun 11, 2011, 6:06:27 AM6/11/11
to comp.lang.python
On 2011.06.11 04:41 AM, Asen Bozhilov 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
d is this case is a dictionary object, and therefore has keys you can
look up (with square brackets). The same is true with lists and tuples
(which have integers as "keys"). An arbitrary object can have arbitrary
values in arbitrary variables in its namespace (accessed with dots).
Objects can have a __dict__ variable that stores the variables in their
namespace as a dictionary (not entirely sure how this works; I'm sure
someone can expand on it).

With:
class simpleObject():
pass
a = simpleObject()

This:
a.key = 'value'
a.otherkey = 'othervalue'

I simpler than:
a.props = {}
a.props['key'] = 'value'
a.props['otherkey'] = 'othervalue'


However, if you want your object to hold several different sets of keys
and respective values, dictionaries (or lists/tuples) make more sense.

Ben Finney

unread,
Jun 11, 2011, 6:11:17 AM6/11/11
to
Asen Bozhilov <asen.b...@gmail.com> writes:

> 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.

Run, don't walk, to the Python Tutorial. Work through each section, do
the examples, experiement to get an understanding of the examples, and
then continue.

<URL:http://docs.python.org/tutorial/>

> In Python it seems square bracket and dot notations lead lookup in
> different "store".

That's right. Square bracket syntax accesses an object's items, dot
syntax accesses an object's attributes.

> 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.

Work through the tutorial from beginning to end to get a good grounding
in this and other fundamentals.

Welcome to the language, and enjoy your learning!

--
\ “Most people, I think, don't even know what a rootkit is, so |
`\ why should they care about it?” —Thomas Hesse, Sony BMG, 2006 |
_o__) |
Ben Finney

Francesco Bochicchio

unread,
Jun 11, 2011, 6:46:02 AM6/11/11
to

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

Asen Bozhilov

unread,
Jun 11, 2011, 10:40:21 AM6/11/11
to
Francesco Bochicchio wrote:

> 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")

It is exactly what I wanted to know. Thank you. I have not examined
classes in Python yet, but when I do it I will understand some new
things. One of the most interesting is, can an object inherit items
trough the parent class? By items I mean items which are accessible
trough square bracket notation.

I really like Pythonic way here. Square bracket and dot notations
allow me to create an object which can be "true" hash map and
meanwhile to support independent methods from its keys. I could have
an item and a property with same names and they won't interfere each
other.

> 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' ).

Yeah, I agree with that. For example in JS exactly square bracket
notation has been invented to dynamic property access. The biggest
question here is why do you need dynamic property access? In language
as JavaScript which is strongly bounded to browser environment, you
could use:

function getForm(formName) {
return document.forms[formName];
}

Another use case is to call a method of object and kept the proper
`this' value. E.g.

obj.x = 10;
obj.method = function () {
return this.x;
};

function callMethod(obj, method) {
return obj[method]();
}

callMethod(obj, 'method'); //10

Of course it could be achieved in different ways and with dot notation
of course.

Thank you very much for the answer.

Terry Reedy

unread,
Jun 11, 2011, 3:49:36 PM6/11/11
to pytho...@python.org
On 6/11/2011 10:40 AM, Asen Bozhilov wrote:

> It is exactly what I wanted to know. Thank you. I have not examined
> classes in Python yet, but when I do it I will understand some new
> things. One of the most interesting is, can an object inherit items
> trough the parent class? By items I mean items which are accessible
> trough square bracket notation.

.attributes are inherited. [index-or-key] items are not.

> I really like Pythonic way here. Square bracket and dot notations
> allow me to create an object which can be "true" hash map and
> meanwhile to support independent methods from its keys. I could have
> an item and a property with same names and they won't interfere each
> other.

Right. d.items is a dict method. d['items'] is whatever you assign.
Named tuples in the collections modules, which allow access to fields
through .name as well as [index], have the name class problem. All the
methods are therefore given leading underscore names to avoid this. [But
there still could be a clash if someone used field names with leading
underscores!] Python reserves and uses __xxx__ for system names just to
avoid clashes.

--
Terry Jan Reedy

Asen Bozhilov

unread,
Jun 11, 2011, 4:41:50 PM6/11/11
to
Terry Reedy wrote:

> Right. d.items is a dict method. d['items'] is whatever you assign.
> Named tuples in the collections modules, which allow access to fields
> through .name as well as [index], have the name class problem. All the
> methods are therefore given leading underscore names to avoid this. [But
> there still could be a clash if someone used field names with leading
> underscores!]  

Scripting languages as JavaScript, Python and other so dynamic
languages allow user to shoot in his feet. I think the developer
should learning the curves of the language before start writing
complex applications. That was the goal of this thread.


0 new messages