Square bracket and dot notations?

Discussion in 'Python' started by Asen Bozhilov, Jun 11, 2011.

  1. 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.
    Asen Bozhilov, Jun 11, 2011
    #1
    1. Advertising

  2. Asen Bozhilov

    Andrew Berg Guest

    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.
    Andrew Berg, Jun 11, 2011
    #2
    1. Advertising

  3. On 11 Giu, 11:41, 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
    >
    > 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
    Francesco Bochicchio, Jun 11, 2011
    #3
  4. 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.
    Asen Bozhilov, Jun 11, 2011
    #4
  5. Asen Bozhilov

    Terry Reedy Guest

    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
    Terry Reedy, Jun 11, 2011
    #5
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    1
    Views:
    1,118
    Victor Bazarov
    May 4, 2007
  2. Wabiloo
    Replies:
    1
    Views:
    827
    Martin Honnen
    Jan 25, 2008
  3. Replies:
    1
    Views:
    2,237
    Pavel Lepin
    Mar 14, 2008
  4. winterTTr
    Replies:
    2
    Views:
    354
    winterTTr
    Apr 29, 2009
  5. Replies:
    6
    Views:
    244
    Thomas 'PointedEars' Lahn
    Dec 12, 2005
Loading...

Share This Page