473,701 Members | 2,442 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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?

Apr 22 '07 #1
13 6026
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?

http://docs.python.org/ref/attribute-access.html

Stefan
Apr 22 '07 #2
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
Apr 22 '07 #3
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...
Apr 22 '07 #4
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)
Apr 22 '07 #5
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
Apr 22 '07 #6
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?
Apr 22 '07 #7
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.
Apr 22 '07 #8
Martin Drautzburg <Ma************ ***@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
Apr 23 '07 #9
Martin Drautzburg <Ma************ ***@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
Apr 23 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
8447
by: ruari mactaggart | last post by:
can i write >>>dictionary to mean the 3rd item in the list that is the corresponding value for 'key' ?
0
1361
by: Till Plewe | last post by:
Is there a way to speed up killing python from within a python program? Sometimes shutting down takes more than 10 times as much time as the actual running of the program. The programs are fairly simple (searching/organizing large boardgame databases) but use a lot of memory (1-6GB). The memory is mostly used for simple structures like trees or relations. Typically there will be a few large dictionaries and many small...
8
2617
by: Frohnhofer, James | last post by:
My initial problem was to initialize a bunch of dictionaries at the start of a function. I did not want to do def fn(): a = {} b = {} c = {} . . . z = {}
3
2370
by: Shivram U | last post by:
Hi, I want to store dictionaries on disk. I had a look at a few modules like bsddb, shelve etc. However would it be possible for me to do the following hash = where the key is an int and not a string bsddb requires that both the key,value are string. shelve does support values being object but not the keys. Is there any
27
2096
by: Ron Adam | last post by:
Hi, I found the following to be a useful way to access arguments after they are passed to a function that collects them with **kwds. class namespace(dict): def __getattr__(self, name): return self.__getitem__(name) def __setattr__(self, name, value): self.__setitem__(name, value) def __delattr__(self, name):
210
10470
by: Christoph Zwerschke | last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I haven't found a satisfying answer yet: Why isn't there an "ordered dictionary" class at least in the standard list? Time and again I am missing that feature. Maybe there is something wrong with my programming style, but I rather think it is generally useful. I fully agree with the following posting where somebody complains why so very basic and useful things are not part...
8
1746
by: placid | last post by:
Hi all, Just wondering if anyone knows how to pop up the dialog that windows pops up when copying/moving/deleting files from one directory to another, in python ? Cheers
1
165
by: Edwin.Madari | last post by:
by the way, iterating over bar will throw KeyError if that key does not exist in foo. to see that in action, simply set another key in bar after copy.deepcopy stmt in this example.. bar = 0 and re-run.... fun learning with python... Edwin -----Original Message----- From: Madari, Edwin Sent: Thursday, August 14, 2008 9:24 PM
14
1813
by: cnb | last post by:
Are dictionaries the same as hashtables?
0
8733
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9223
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9083
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8934
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5904
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4662
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3102
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2398
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.