473,698 Members | 2,203 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting a dictionary from an object

Hello.

I would like to have a quick way to create dicts from object, so that a
call to foo['bar'] would return obj.bar.

The following works, but I would prefer to use a built-in way if one
exists. Is there one?

Thanks in advance.

class dictobj(dict):
"""
class dictobj(dict):
A dictionary d with an object attached to it,
which treats d['foo'] as d.obj.foo.
"""
def __init__(self, obj):
self.obj = obj
def __getitem__(sel f, key):
return self.obj.__geta ttribute__(key)

--
Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
Jul 23 '05
31 2573
On Sat, Jul 23, 2005 at 06:59:43PM -0600, Steven Bethard wrote:
Thanos Tsouanas wrote:
I would like to have a quick way to create dicts from object, so that a
call to foo['bar'] would return obj.bar.

The following works, but I would prefer to use a built-in way if one
exists. Is there one?


Maybe I'm not understanding your problem, but have you looked at the
builtin "vars()"?


I didn't know about it, but I knew about object.__dict__ which is, as I
see equivalent with vars(object). But it doesn't do the job for me,
since it fails to grab all obj.foo's, some of them being properties,
etc.

vars() is good to know though, Thanks!

--
Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
Jul 24 '05 #11
Thanos Tsouanas a écrit :
On Sun, Jul 24, 2005 at 01:43:43PM +1000, Steven D'Aprano wrote:
(snip)
Why jump through all those hoops to get attributes when Python already
provides indexing and attribute grabbing machinery that work well? Why do
you bother to subclass dict, only to mangle the dict __getitem__ method so
that you can no longer retrieve items from the dict?

Because *obviously* I don't know of these indexing and attribute
grabbing machineries you are talking about in my case. If you cared to
read my first post, all I asked was for the "normal", "built-in" way to
do it. Now, is there one, or not?


If you re-read your first post, you'll notice that you didn't say
anything about the intention, only about implementation !-)

Now if your *only* need is to access object as a dict for formated
output, you don't need to subclass dict. This is (well, should be) enough:

class Wrapper(object) :
def __init__(self, obj):
self._obj = obj
def __getitem__(sel f, name):
return getattr(self._o bj, name)

This works with 'normal' attributes as well as with properties. Notice
that this wrapper is read-only, and don't pretend to be a real
dictionnary - but still it implements the minimum required interface for
"%(attname) s" like formatting.

HTH
Bruno
Jul 24 '05 #12
On Sun, Jul 24, 2005 at 02:01:30PM +0200, Bruno Desthuilliers wrote:
Thanos Tsouanas a écrit :
On Sun, Jul 24, 2005 at 01:43:43PM +1000, Steven D'Aprano wrote:

Because *obviously* I don't know of these indexing and attribute
grabbing machineries you are talking about in my case. If you cared to
read my first post, all I asked was for the "normal", "built-in" way to
do it. Now, is there one, or not?
If you re-read your first post, you'll notice that you didn't say
anything about the intention, only about implementation !-)


"""The following works, but I would prefer to use a built-in way if one
exists. Is there one?"""
Now if your *only* need is to access object as a dict for formated
output, you don't need to subclass dict. This is (well, should be) enough:

class Wrapper(object) :
def __init__(self, obj):
self._obj = obj
def __getitem__(sel f, name):
return getattr(self._o bj, name)

This works with 'normal' attributes as well as with properties. Notice
that this wrapper is read-only, and don't pretend to be a real
dictionnary - but still it implements the minimum required interface for
"%(attname) s" like formatting.
Thanks!! You made clear what 'the extra functionality' was. Indeed
there is no need to subclass dict...
HTH
it does!
Bruno
--
http://mail.python.org/mailman/listinfo/python-list


--
Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
Jul 24 '05 #13
Bruno Desthuilliers a écrit :
(snip)
class Wrapper(object) :
def __init__(self, obj):
self._obj = obj
def __getitem__(sel f, name):
return getattr(self._o bj, name)


If you want the Wrapper to be more like a Decorator (ie still can use
the Wrapper object as if it was the wrapped object), you can add this:

def __getattr__(sel f, name):
return getattr(self._o bj, name)

def __setattr__(sel f, name, val):
if name == '_obj':
super(Wrapper, self).__setattr __(name, val)
else:
setattr(self._o bj, name, val)

The Python cookbook may have some receipes too for this kind of funny
things...
Jul 24 '05 #14
Steven D'Aprano a écrit :
On Sun, 24 Jul 2005 02:09:54 +0300, Thanos Tsouanas wrote:

(snip)
Are you telling me that the ONLY thing you use dictobj objects for is to
print them?

I don't think so. I do know how to print an object, amazingly.

Perhaps you would like to explain how you use the rest of the
functionality of the dictobj, instead of taking my words out of context
and giving an inane answer.

Why jump through all those hoops to get attributes when Python already
provides indexing and attribute grabbing machinery that work well? Why do
you bother to subclass dict, only to mangle the dict __getitem__ method so
that you can no longer retrieve items from the dict?


The idea of the OP is not to use the dictobj as a full fledged dict,
just to wrap the obj in something that is dict-like enough to be used
for "%(attname) s" formatting. I also assume that he doesn't want to
manually alter the code of each and every class to achieve this !-)

So we can certainly agree that subclassing dict here is overkill and a
bit misleading, but there are probably better ways to express this
feeling. Of course, it would have been simpler if the OP had tell us
from the start what was it's use case, but what...

One could of course use metaclass tricks and the like to customize the
objects __str__ or __repr__ (as in David Mertz's gnosis.magic package),
but that would be overkill too IMHO.

The plain old Decorator[1] pattern is probably enough in this case,
since it's quite easy to implement a generic Decorator in Python.
Another solution could be to dynamically modify the to-be-wrapped
object's class to add a __getitem__ method.

Jul 24 '05 #15
Thanos Tsouanas a écrit :
On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote:
Hello.

I would like to have a quick way to create dicts from object, so that a
call to foo['bar'] would return obj.bar.

(snip)
print foo %do

where do is a dictobj object...


I gave you a solution based on the Decorator pattern in another post,
but there is also the possibility to add a __getitem__ method directly
to the to-be-formatted object's class:

def mygetitem(obj, name):
return getattr(obj, name)

setattr(obj.__c lass__, '__getitem__', mygetitem)
obj['bar']
<meta>
BTW, parts of this thread should remind us all that it's usually better
to clearly describe the *problem* before asking for comments on the
solution...
</meta>

My 2 cents...
Bruno

Jul 24 '05 #16
On Sun, Jul 24, 2005 at 03:01:40PM +0200, Bruno Desthuilliers wrote:
I gave you a solution based on the Decorator pattern in another post,
but there is also the possibility to add a __getitem__ method directly
to the to-be-formatted object's class:

def mygetitem(obj, name):
return getattr(obj, name)

setattr(obj.__c lass__, '__getitem__', mygetitem)
obj['bar']
I used what you suggested earlier with the Wrapper, without subclassing
dict anymore. Thanks!
<meta>
BTW, parts of this thread should remind us all that it's usually better
to clearly describe the *problem* before asking for comments on the
solution...
</meta>


"""I would like to have a quick way to create dicts from object, so
that a call to foo['bar'] would return obj.bar."""

Actually this is the problem, (I never said anything about _assigning_
new keys in foo), and the line following it is my question ;)

Thanks again!

--
Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
Jul 24 '05 #17
Thanos Tsouanas a écrit :
On Sun, Jul 24, 2005 at 02:01:30PM +0200, Bruno Desthuilliers wrote:

(snip)
If you re-read your first post, you'll notice that you didn't say
anything about the intention, only about implementation !-)


"""The following works, but I would prefer to use a built-in way if one
exists. Is there one?"""


This is about the " how", not about the "why". The "why" is:
fmt_string % dictobj

BTW, there are many templating solutions in Python, that are heavier but
may (or may not, depending on the context) scale better or be more
usable than string formatting...

Bruno
Jul 24 '05 #18
On Sun, 24 Jul 2005 12:03:47 +0300, Thanos Tsouanas wrote:
On Sun, Jul 24, 2005 at 01:43:43PM +1000, Steven D'Aprano wrote:
On Sun, 24 Jul 2005 02:09:54 +0300, Thanos Tsouanas wrote:
>
> print foo %do
>
> where do is a dictobj object...
Are you telling me that the ONLY thing you use dictobj objects for is to
print them?


I'm sorry to disappoint you, but yes. When you have a long text
template to fill-out, with lots of %(foo)s, and all those foos are
attributes of an object, it really helps to have dictobj.


Ah, now we're making progress in finding out what the purpose of the
dictobj is! Thank you, this is starting to become clearer now.
I don't think so. I do know how to print an object, amazingly.


Please, tell me, how would you print it in my case?


If I have understood you, you have some object like such:

obj.foo = 1
obj.bar = 2
obj.spam = 'a'
obj.eggs = 'b'

say.

You want to use it something like this:

print "My object has fields %(foo)s; %(bar)s; %(spam)s; %(eggs)s." % obj

except that doesn't work. So I would simply change the reference to obj to
obj.__dict__ and it should do exactly what you want.

Does that help?

[snip] Because *obviously* I don't know of these indexing and attribute
grabbing machineries you are talking about in my case. If you cared to
read my first post, all I asked was for the "normal", "built-in" way to
do it. Now, is there one, or not?


I did read your first post. Unfortunately, you had not explained what you
were trying to do very well. Your initial solution involved sub-classing
dict. I made the fatal mistake of trying to guess what you needed from
your sample code -- a natural mistake to make, given how vague your
requirements were. Or rather, non-existent.

It really does help to explain what your functional requirements are,
instead of focusing on one, possibly pointless, implementation.

If I have understood your functional requirements correctly, you don't
need "to have a quick way to create dicts from object, so that a call to
foo['bar'] would return obj.bar" at all.

--
Steven.

Jul 24 '05 #19
On Sun, 24 Jul 2005 12:07:02 +0300, Thanos Tsouanas wrote:
On Sat, Jul 23, 2005 at 06:59:43PM -0600, Steven Bethard wrote:
Thanos Tsouanas wrote:
> I would like to have a quick way to create dicts from object, so that a
> call to foo['bar'] would return obj.bar.
>
> The following works, but I would prefer to use a built-in way if one
> exists. Is there one?


Maybe I'm not understanding your problem, but have you looked at the
builtin "vars()"?


I didn't know about it, but I knew about object.__dict__ which is, as I
see equivalent with vars(object). But it doesn't do the job for me,
since it fails to grab all obj.foo's, some of them being properties,
etc.


You could have mentioned this earlier.

But I don't think you are correct. As far as I can see, properties do have
an entry in obj.__dict__ the same as other attributes, although there is
certainly some strangeness going on with properties.

Using the sample code from here:
http://www.python.org/2.2.3/descrintro.html#property

class C(object):
def __init__(self):
self.__x = 0
def getx(self):
return self.__x
def setx(self, x):
if x < 0: x = 0
self.__x = x
x = property(getx, setx)

I see _C__x in C().__dict__, exactly as expected. (The _C is Python's
standard name mangling of "semi-private" attributes starting with double
underscores.)

I can't see any way to inspect a Python object and get a list of
properties, so you might have to keep your own list: add a class-attribute
of your object which keeps a list of all the properties:

class Obj:
# various methods, attributes and properties
...
# keep a list of special properties that don't show
# up correctly in __dict__
special = ['foo', 'bar']

# now define a special method that makes a copy of
# __dict__ and adds special properties to it

def objdict(self):
D = self.__dict__.c opy()
# assume shallow copy is enough
for property_name in self.special:
D[property_name] = self.__getattri bute__(property _name)
return D

then call it when you need it:

print "My object has fields %(foo)s and %(bar)s." % obj.objdict()
It would be nice to see an easier way to introspect objects and get
a list of properties.
--
Steven.

Jul 24 '05 #20

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

Similar topics

1
3586
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148 respectively In the sample code you see that I have class Item and class Dict class Dict contains a dictionary called items. The items dictionary will contain instances of Item that are keyed off of the Item name. In __main__ I create two...
26
4055
by: Alan Silver | last post by:
Hello, I have a server running Windows Server 2003, on which two of the web sites use the MegaBBS ASP forum software. Both sites suddenly developed the same error, which seems to be connected to the dictionary object. After some tinkering, I whittled it down to the following (complete) ASP... <%@ CodePage=65001 Language="VBScript"%>
5
14799
by: David Rasmussen | last post by:
If I have a string that contains the name of a function, can I call it? As in: def someFunction(): print "Hello" s = "someFunction" s() # I know this is wrong, but you get the idea... /David
2
15941
by: ESPNSTI | last post by:
Hi, I'm trying to use a generics dictionary with a key class that implements and needs IComparable<>. However when I attempt to use the dictionary, it doesn't appear to use the IComparable<> to find the key. In the example below, accessing the dictionary by using the exact key object that was used to add to the dictionary works. (see code comment 1). However, if I attempt to access the dictionary by using a key object that
2
3419
by: jg | last post by:
I was trying to get custom dictionary class that can store generic or string; So I started with the example given by the visual studio 2005 c# online help for simpledictionay object That seem to miss a few things including #endregion directive and the ending class } Is there not a simple way like in dotnet vb? I managed to get the sample to code to this:
4
2321
by: Betina Andersen | last post by:
I have a dictionary object, then I create a new dictionary object and sets it equal to my original, then I pass the new dictionary object to a function that changes some of my values - but then my original dictionary also gets changed and that was not the intention, can someone explain to me why it behaves that way and how do I avoid it, så I van have different dictionary objects? Thanks Betina
5
21607
by: randy1200 | last post by:
I have the following: Dictionary<object, stringd = new Dictionary<object, string>(); I can add entries to the dictionary, and I can loop through the entries I've added to the Dictionary. This all works great. My question is: I'd like to find a way to get just the first key, without looping through the whole Dictionary. I tried the code below, but I get a compile error trying to use an index value on the KeyCollection:
4
14742
by: NullQwerty | last post by:
Hi folks, I have a Dictionary which contains a string key and an object value. I want the object value to point to a property in my class and I want it to be by reference, so that later on I can change the value of the property through the dictionary. I am having difficulty making the value be by reference. Is this possible? I've even tried unsuccessfully to use unsafe code with pointers.
6
10174
by: GiJeet | last post by:
hello, I'm trying to use a dictionary as a class member. I want to use a property to get/set the key/value of the dictionary but I'm confused as how to use a dictionary as a property. Since there are 2 parts, I don't know how to setup the get/sets. I tried searching but could not find any examples. I'd appreciate an example of how to get/ set the two parts of a dictionary via a property of a class. tia
0
8600
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9156
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
9021
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...
1
8892
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6518
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4361
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4614
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3038
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
2323
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.