473,696 Members | 1,827 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 2571
Steven D'Aprano a écrit :
On Sun, 24 Jul 2005 12:03:47 +0300, Thanos Tsouanas wrote:

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.


Nope, it doesn't work with computed attributes (properties, descriptors,
....).

The most obvious solution is the decorator pattern - which is somewhat
the op was trying to do.

Another solution is to dynamically add a __getitem__ method to obj
before using'em that way, either by setting explicitly the method as an
attribute of the object's class or by using the import_with_met aclass()
trick from David Mertz.

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

+1 on this !-)
Jul 24 '05 #21
Steven D'Aprano a écrit :
On Sun, 24 Jul 2005 12:07:02 +0300, Thanos Tsouanas wrote:
Thanos Tsouanas wrote:
(snip)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.

(snip) 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. (snip)
Yes, but you don't see 'x'. Poking into the object's __dict__ would
defeat the whole point of computed attributes - which by the way need
not directly map to a protected or private variable, nor even be
properties (think: descriptors).
I can't see any way to inspect a Python object and get a list of
properties,
I do :

def list_properties (obj):
proptype = type(property() ) # not defined in types
klass = obj.__class__
names = dir(klass) # so we get inherited attribs as well
d = dict([(name, getattr(klass, name)) for name in names])
return [name for name, attrib in d.items() \
if type(attrib) is proptype]

Note that this won't find all descriptors (I've tried and it really
harder... there are a lot of things in a class.__dict__ that have a
__get__() method, most of'em not defined in the types module).

Anyway, you won't need it... (I mean, the OP don't need it to solve it's
problem)
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()
This means adding responsabilitie s to the class when the need is
obviously orthogonal to the class's responsabilitie s. Implementing a
generic decorator pattern in Python does'nt require more code, doesn't
requires the class nor the object to be modified at all, is probably
more robust, and is, well... more generic !-) (should I say 'more
pythonic' ?)
It would be nice to see an easier way to introspect objects and get
a list of properties.


You're dream is now reality. Now ain't *that* nice ?-)

Bruno
Jul 24 '05 #22
On Sun, 24 Jul 2005 15:52:50 +0300, Thanos Tsouanas <th****@sians.o rg>
declaimed the following in comp.lang.pytho n:
On Sun, Jul 24, 2005 at 03:01:40PM +0200, Bruno Desthuilliers wrote:
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 ;)

No... That is a description of a proposed/desired implementation
with no real Use-Case... If you'd shown something similar to a print
statement with an explanation

print "%(this)s or %(that)" % obj
#desire obj to behave as a dict for this type of print

you'd likely have gotten much faster or more applicable responses.

-- =============== =============== =============== =============== == <
wl*****@ix.netc om.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
=============== =============== =============== =============== == <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.ne tcom.com/> <

Jul 24 '05 #23
Thanos Tsouanas wrote:
Steven Bethard wrote:
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.


How about something like:
dict((name, getattr(obj, name)) for name in dir(obj))

For example:

py> class C(object):
.... x = 1
.... @property
.... def y(self):
.... return 2
.... def __init__(self):
.... self.z = 3
....
py> c = C()
py> d = dict((name, getattr(c, name)) for name in dir(c))
py> d['x']
1
py> d['y']
2
py> d['z']
3

Looks like this will get instance attributes, class attributes and
properties just fine.

STeVe
Jul 24 '05 #24
*Grandmaster* Steven Bethard a écrit :

How about something like:
dict((name, getattr(obj, name)) for name in dir(obj))


....

voiceless-ly'rs
Jul 24 '05 #25
> voiceless-ly'rs
What does this mean?? Just curious (googled that and ly'rs and didnt
find anything relevant)
--
Dark Cowherd
Jul 25 '05 #26
Dark Cowherd wrote:
voiceless-ly'rs


What does this mean?? Just curious (googled that and ly'rs and didnt
find anything relevant)


The voiceless part I understand to mean that Bruno is "shocked and
stunned and not a little bit amazed" [1] at Steven's masterstroke which
came out of the blue and trumped all previous efforts -- a true "deus ex
machina", a thunderbolt from Olympus -- or if you want a one-word
colloquialism, he's gobsmacked.

The -ly'rs part means that in his shocked state he has tried to emulate
the timbot's characteristic sign-off [2], but failed to get the syntax
correct.

[1] Billy Connolly
[2] http://www.python.org/tim_one/ ... or just check out a few postings
by Tim Peters in this newsgroup.
Jul 25 '05 #27
John Machin wrote:
Dark Cowherd wrote:
voiceless-ly'rs

What does this mean?? Just curious (googled that and ly'rs and didnt
find anything relevant)


s/ly'rs/ly y'rs/
The voiceless part I understand to mean that Bruno is "shocked and
stunned and not a little bit amazed" [1] at Steven's masterstroke which
came out of the blue and trumped all previous efforts -- a true "deus ex
machina", a thunderbolt from Olympus -- or if you want a one-word
colloquialism, he's gobsmacked.

The -ly'rs part means that in his shocked state he has tried to emulate
the timbot's characteristic sign-off [2], but failed to get the syntax
correct.


one-hundred-percent-correct-ly y'rs !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 25 '05 #28
On Sun, Jul 24, 2005 at 02:14:15PM -0600, Steven Bethard wrote:

How about something like:
dict((name, getattr(obj, name)) for name in dir(obj))
Pretty!!!
Looks like this will get instance attributes, class attributes and
properties just fine.


But not SQLObject's objects...
Any idea why? (Getting attribute errors, it seems that these
"attributoi ds" are not listed in dir(obj), so i have to use my ugly
dictobj class.. :(

--
Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
Jul 25 '05 #29
Thanos Tsouanas wrote:
On Sun, Jul 24, 2005 at 02:14:15PM -0600, Steven Bethard wrote:
How about something like:
dict((name, getattr(obj, name)) for name in dir(obj))


Pretty!!!
Looks like this will get instance attributes, class attributes and
properties just fine.


But not SQLObject's objects...
Any idea why? (Getting attribute errors, it seems that these
"attributoi ds" are not listed in dir(obj), so i have to use my ugly
dictobj class.. :(


I don't know how SQLObjects are implemented, but I'm guessing they use
__getattr__ or __getattribute_ _:

py> class C(object):
.... w = 1
.... @property
.... def x(self):
.... return 2
.... def __init__(self):
.... self.y = 3
.... def __getattr__(sel f, name):
.... if name == 'z':
.... return 4
....
py> c = C()
py> d = dict((name, getattr(c, name)) for name in dir(c))
py> d['w'], d['x'], d['y']
(1, 2, 3)
py> d['z']
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
KeyError: 'z'

Any attribute simulated through __getattr__ or __getattribute_ _ cannot
be found by dir():

py> dir(c)
['__class__', '__delattr__', '__dict__', '__doc__', '__getattr__',
'__getattribute __', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__' , '__repr__', '__setattr__', '__str__',
'__weakref__', 'w', 'x', 'y']

For this reason, I try to avoid implementing attributes through these
methods, but sometimes it's unavoidable.

STeVe
Jul 26 '05 #30

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
14798
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
8597
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
9145
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
9010
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
8880
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,...
0
8853
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
7703
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
4356
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
4611
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3033
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

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.