Getting a dictionary from an object

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Jul 24 09:29:14 EDT 2005


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.




More information about the Python-list mailing list