Square bracket and dot notations?

A

Asen Bozhilov

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

Andrew Berg

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

Francesco Bochicchio

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
 
A

Asen Bozhilov

Francesco said:
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.
 
T

Terry Reedy

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top