473,386 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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":"something"}

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 5984
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":"something"}

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":"something"}

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":"something"}

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":"something"}

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__.update(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":"something"}

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.dewrites:
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__.update(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
Alex Martelli wrote:
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__.update(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.

Apr 23 '07 #11
En Mon, 23 Apr 2007 03:14:32 -0300, Martin Drautzburg
<Ma***************@web.deescribió:
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
Apr 23 '07 #12
On 2007-04-22, Martin Drautzburg <Ma***************@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__(self, 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
Apr 23 '07 #13
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.
Apr 23 '07 #14

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

Similar topics

6
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
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...
8
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
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...
27
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...
210
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...
8
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
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...
14
by: cnb | last post by:
Are dictionaries the same as hashtables?
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...

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.