Dictionaries and dot notation

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Martin Drautzburg

    #1

    Dictionaries and dot notation

    This may be pretty obvious for most of you:

    When I have an object (an instance of a class "Foo") I can access
    attributes via dot notation:

    aFoo.bar

    however when I have a dictionary

    aDict = {"bar":"somethi ng"}

    I have to write

    aDict["bar"]

    What if I want to create a datastructure that can be used in dot
    notation without having to create a class, i.e. because those objects
    have no behavior at all?

    I know that accessing an instance variable via bracket notation would
    really have to be written as:

    aFoo.__dict__['bar']

    but this does not bring me any further, because I would still have to
    plug in that __dict__ thing into my datastructure, which leads us to
    the same question as above.

    Can anyone tell me what I am missing here?

  • Stefan Behnel

    #2
    Re: Dictionaries and dot notation

    Martin Drautzburg wrote:
    This may be pretty obvious for most of you:
    >
    When I have an object (an instance of a class "Foo") I can access
    attributes via dot notation:
    >
    aFoo.bar
    >
    however when I have a dictionary
    >
    aDict = {"bar":"somethi ng"}
    >
    I have to write
    >
    aDict["bar"]
    >
    What if I want to create a datastructure that can be used in dot
    notation without having to create a class, i.e. because those objects
    have no behavior at all?
    >
    I know that accessing an instance variable via bracket notation would
    really have to be written as:
    >
    aFoo.__dict__['bar']
    >
    but this does not bring me any further, because I would still have to
    plug in that __dict__ thing into my datastructure, which leads us to
    the same question as above.
    >
    Can anyone tell me what I am missing here?
    This?



    Stefan

    Comment

    • Daniel Nogradi

      #3
      Re: Dictionaries and dot notation

      This may be pretty obvious for most of you:

      When I have an object (an instance of a class "Foo") I can access
      attributes via dot notation:

      aFoo.bar

      however when I have a dictionary

      aDict = {"bar":"somethi ng"}

      I have to write

      aDict["bar"]

      What if I want to create a datastructure that can be used in dot
      notation without having to create a class, i.e. because those objects
      have no behavior at all?

      I know that accessing an instance variable via bracket notation would
      really have to be written as:

      aFoo.__dict__['bar']

      but this does not bring me any further, because I would still have to
      plug in that __dict__ thing into my datastructure, which leads us to
      the same question as above.

      Can anyone tell me what I am missing here?

      What's wrong with creating a dummy class?

      class data:
      pass

      mydata = data( )
      mydata.foo = 'foo'
      mydata.bar = 'bar'

      print mydata.foo
      print mydata.bar



      Daniel

      Comment

      • Bruno Desthuilliers

        #4
        Re: Dictionaries and dot notation

        Martin Drautzburg a écrit :
        This may be pretty obvious for most of you:
        >
        When I have an object (an instance of a class "Foo") I can access
        attributes via dot notation:
        >
        aFoo.bar
        >
        however when I have a dictionary
        >
        aDict = {"bar":"somethi ng"}
        >
        I have to write
        >
        aDict["bar"]
        >
        What if I want to create a datastructure that can be used in dot
        notation without having to create a class, i.e. because those objects
        have no behavior at all?
        A class inheriting from dict and implementing __getattr__ and
        __setattr__ should do the trick...

        Comment

        • Bruno Desthuilliers

          #5
          Re: Dictionaries and dot notation

          Bruno Desthuilliers a écrit :
          Martin Drautzburg a écrit :
          >
          >This may be pretty obvious for most of you:
          >>
          >When I have an object (an instance of a class "Foo") I can access
          >attributes via dot notation:
          >>
          > aFoo.bar
          >>
          >however when I have a dictionary
          > aDict = {"bar":"somethi ng"}
          >>
          >I have to write
          >>
          > aDict["bar"]
          >>
          >What if I want to create a datastructure that can be used in dot
          >notation without having to create a class, i.e. because those objects
          >have no behavior at all?
          >
          >
          A class inheriting from dict and implementing __getattr__ and
          __setattr__ should do the trick...

          Oh, yes, if you don't care about dict-like behaviour, you can also just:

          class Data(object):
          def __init__(self, **kw):
          self.__dict__.u pdate(kw)


          Comment

          • Daniel Nogradi

            #6
            Re: Dictionaries and dot notation

            This may be pretty obvious for most of you:

            When I have an object (an instance of a class "Foo") I can access
            attributes via dot notation:

            aFoo.bar

            however when I have a dictionary

            aDict = {"bar":"somethi ng"}

            I have to write

            aDict["bar"]

            What if I want to create a datastructure that can be used in dot
            notation without having to create a class, i.e. because those objects
            have no behavior at all?
            >
            A class inheriting from dict and implementing __getattr__ and
            __setattr__ should do the trick...

            It can do the trick but one has to be careful with attributes that are
            used by dict such as update, keys, pop, etc. Actually it's noted in a
            comment at http://aspn.activestate.com/ASPN/Coo.../Recipe/361668
            why the whole idea (attribute access of dictionaries) is a bad idea
            and I tend to agree.

            Daniel

            Comment

            • Martin Drautzburg

              #7
              Re: Dictionaries and dot notation

              mydata = data( )
              mydata.foo = 'foo'
              mydata.bar = 'bar'
              >
              print mydata.foo
              print mydata.bar
              I am aware of all this.
              Okay let me rephrase my question: is there a way of using dot notation
              without having to create a class?

              Comment

              • Martin Drautzburg

                #8
                Re: Dictionaries and dot notation

                Daniel Nogradi wrote:

                What if I want to create a datastructure that can be used in dot
                notation without having to create a class, i.e. because those
                objects have no behavior at all?
                >>
                >A class inheriting from dict and implementing __getattr__ and
                >__setattr__ should do the trick...
                >
                >
                It can do the trick but one has to be careful with attributes that are
                used by dict such as update, keys, pop, etc. Actually it's noted in a
                comment at
                http://aspn.activestate.com/ASPN/Coo.../Recipe/361668 why the
                whole idea (attribute access of dictionaries) is a bad idea and I tend
                to agree.
                Oh thank you. So all I have to do is have my object's class implement
                __setattr__ and __getattr__, or derive it from a class that does so?
                And I could save my "attributes " anywhere within my instance variables.
                So I could even add a dictionary whose name does not conflict with what
                python uses and whose key/value pairs hold the attributes I want to
                access with dot notation and delegate all the python attributes to
                their native positions? Oh I see, thats tricky. I still need to be
                aware of the builtin stuff one way or the other.

                Interesting.

                Comment

                • Ben Finney

                  #9
                  Re: Dictionaries and dot notation

                  Martin Drautzburg <Martin.Drautzb urg@web.dewrite s:
                  Okay let me rephrase my question: is there a way of using dot
                  notation without having to create a class?
                  Dot notation, e.g. 'foo.bar', is parsed by the interpreter as "access
                  the attribute named 'bar' of the object 'foo'". Objects have
                  attributes either by virtue of the class having them, or the object
                  getting them assigned after creation.

                  Can you describe what you would change in the above, or can you
                  re-word your request based on these facts?

                  --
                  \ "Our products just aren't engineered for security." -- Brian |
                  `\ Valentine, senior vice-president of Microsoft Windows |
                  _o__) development |
                  Ben Finney

                  Comment

                  • Alex Martelli

                    #10
                    Re: Dictionaries and dot notation

                    Martin Drautzburg <Martin.Drautzb urg@web.dewrote :
                    mydata = data( )
                    mydata.foo = 'foo'
                    mydata.bar = 'bar'

                    print mydata.foo
                    print mydata.bar
                    >
                    I am aware of all this.
                    Okay let me rephrase my question: is there a way of using dot notation
                    without having to create a class?
                    Sure, all you need to create is an *INSTANCE* of a suitable type or
                    class. For example:
                    >>d = dict(foo=23, bar=45)
                    >>m = new.module('for _martin')
                    >>m.__dict__.up date(d)
                    >>m.foo
                    23
                    >>m.bar
                    45
                    >>>
                    A module may be appropriate, since it's little more than a "wrapper
                    around a dict to access items by dot notation":-).


                    Alex

                    Comment

                    • Martin Drautzburg

                      #11
                      Re: Dictionaries and dot notation

                      Alex Martelli wrote:
                      Martin Drautzburg <Martin.Drautzb urg@web.dewrote :
                      >
                      mydata = data( )
                      mydata.foo = 'foo'
                      mydata.bar = 'bar'
                      >
                      print mydata.foo
                      print mydata.bar
                      >>
                      >I am aware of all this.
                      >Okay let me rephrase my question: is there a way of using dot
                      >notation without having to create a class?
                      >
                      Sure, all you need to create is an *INSTANCE* of a suitable type or
                      class. For example:
                      >
                      >>>d = dict(foo=23, bar=45)
                      >>>m = new.module('for _martin')
                      >>>m.__dict__.u pdate(d)
                      >>>m.foo
                      23
                      >>>m.bar
                      45
                      >>>>
                      >
                      A module may be appropriate, since it's little more than a "wrapper
                      around a dict to access items by dot notation":-).
                      Thanks, I finally got it. Even your previous example actually does the
                      trick. I did not notice that I can use a single class (or a module) for
                      all my datastructures, because I can "plug in" new attributes into the
                      instance without the class knowing about them.

                      I was mistaken to believe that I had to know about attributes at the
                      time of class creation. But your expample does not require that. Should
                      have read this more carefully.

                      Comment

                      • Gabriel Genellina

                        #12
                        Re: Dictionaries and dot notation

                        En Mon, 23 Apr 2007 03:14:32 -0300, Martin Drautzburg
                        <Martin.Drautzb urg@web.deescri bió:
                        I did not notice that I can use a single class (or a module) for
                        all my datastructures, because I can "plug in" new attributes into the
                        instance without the class knowing about them.
                        >
                        I was mistaken to believe that I had to know about attributes at the
                        time of class creation. But your expample does not require that. Should
                        have read this more carefully.
                        Welcome to Python and its dynamic nature!

                        --
                        Gabriel Genellina

                        Comment

                        • Antoon Pardon

                          #13
                          Re: Dictionaries and dot notation

                          On 2007-04-22, Martin Drautzburg <Martin.Drautzb urg@web.dewrote :
                          Daniel Nogradi wrote:
                          >
                          >
                          >What if I want to create a datastructure that can be used in dot
                          >notation without having to create a class, i.e. because those
                          >objects have no behavior at all?
                          >>>
                          >>A class inheriting from dict and implementing __getattr__ and
                          >>__setattr__ should do the trick...
                          >>
                          >>
                          >It can do the trick but one has to be careful with attributes that are
                          >used by dict such as update, keys, pop, etc. Actually it's noted in a
                          >comment at
                          >http://aspn.activestate.com/ASPN/Coo.../Recipe/361668 why the
                          >whole idea (attribute access of dictionaries) is a bad idea and I tend
                          >to agree.
                          >
                          Oh thank you. So all I have to do is have my object's class implement
                          __setattr__ and __getattr__, or derive it from a class that does so?
                          And I could save my "attributes " anywhere within my instance variables.
                          So I could even add a dictionary whose name does not conflict with what
                          python uses and whose key/value pairs hold the attributes I want to
                          access with dot notation and delegate all the python attributes to
                          their native positions? Oh I see, thats tricky. I still need to be
                          aware of the builtin stuff one way or the other.
                          Maybe you can do the opposite and create a class that implements
                          __getitem__ and __setitem__ in function of attribute access.

                          The following is an example:

                          class Rec(object):
                          def __init__(__, **kwargs):
                          for key,value in kwargs.items():
                          setattr(__, key, value)

                          def __getitem__(sel f, key):
                          return getattr(self, key)

                          def __setitem__ (self, key, val):
                          setattr(self, key, val)


                          rec = Rec(a=1)

                          print rec.a
                          print rec["a"]

                          rec.b = 2
                          print rec["b"]

                          rec["c"] = 3
                          print rec.c

                          --
                          Antoon Pardon

                          Comment

                          • Bruno Desthuilliers

                            #14
                            Re: Dictionaries and dot notation

                            Martin Drautzburg a écrit :
                            Daniel Nogradi wrote:
                            >
                            >
                            >
                            >>>>What if I want to create a datastructure that can be used in dot
                            >>>>notation without having to create a class, i.e. because those
                            >>>>objects have no behavior at all?
                            >>>
                            >>>A class inheriting from dict and implementing __getattr__ and
                            >>>__setattr_ _ should do the trick...
                            >>
                            >>
                            >>It can do the trick but one has to be careful with attributes that are
                            >>used by dict such as update, keys, pop, etc. Actually it's noted in a
                            >>comment at
                            >>http://aspn.activestate.com/ASPN/Coo.../Recipe/361668 why the
                            >>whole idea (attribute access of dictionaries) is a bad idea and I tend
                            >>to agree.
                            >
                            >
                            Oh thank you. So all I have to do is have my object's class implement
                            __setattr__ and __getattr__, or derive it from a class that does so?
                            And I could save my "attributes " anywhere within my instance variables.
                            So I could even add a dictionary whose name does not conflict with what
                            python uses and whose key/value pairs hold the attributes I want to
                            access with dot notation and delegate all the python attributes to
                            their native positions? Oh I see, thats tricky. I still need to be
                            aware of the builtin stuff one way or the other.
                            Yeps. FWIW, Daniel is right to raise a warning here, and I should have
                            think one more minute before posting - since in fact in this case you
                            don't care about dict-like behaviour.

                            Interesting.

                            Comment

                            Working...