473,737 Members | 1,913 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

assigning a custom mapping type to __dict__

I tried to Google for past discussion on this topic, but without much
luck. If this has been discussed before, I'd be grateful for a pointer.

Does anyone know why you can't assign a custom mapping type to an
object's __dict__?

py> class M(object):
.... def __getitem__(sel f, key):
.... return 42
.... def __setitem__(sel f, key, value):
.... pass
....
py> class C(object):
.... pass
....
py> c = C()
py> c.__dict__ = M()
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: __dict__ must be set to a dictionary

I looked at the source in typeobject.c (where this error originates),
but I'm not fluent enough in CPython yet to be able to tell why a true
dict type is preferred here over just a mapping type...

STeVe
Jul 18 '05 #1
8 4708
Why not just inherit from dict? That seems to work.
class M(dict): .... def __getitem__(sel f,key):
.... return 42
.... def __setitem__(sel f,key,value):
.... pass
.... class C(object): .... pass
.... c = C()
c.__dict__ = M()
c.__dict__['x']
42

-Dan

Steven Bethard wrote:
I tried to Google for past discussion on this topic, but without much
luck. If this has been discussed before, I'd be grateful for a pointer.

Does anyone know why you can't assign a custom mapping type to an
object's __dict__?

py> class M(object):
... def __getitem__(sel f, key):
... return 42
... def __setitem__(sel f, key, value):
... pass
...
py> class C(object):
... pass
...
py> c = C()
py> c.__dict__ = M()
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: __dict__ must be set to a dictionary

I looked at the source in typeobject.c (where this error originates),
but I'm not fluent enough in CPython yet to be able to tell why a true
dict type is preferred here over just a mapping type...

STeVe

Jul 18 '05 #2
Daniel Cer wrote:
Why not just inherit from dict? That seems to work.


Because that isn't the question - Steven knows how to make it work, what he's
curious about is why things are the way they are :)

Anyway, a quick look suggests that it is due to typeobject.c using the concrete
PyDict_* API calls [1] to manipulate tp_dict, rather than the abstract
PyMapping_* calls [2]. The reason behind using the concrete API is, presumably,
a question of speed :)

Cheers,
Nick.

[1] http://www.python.org/dev/doc/devel/...ctObjects.html
[2] http://www.python.org/dev/doc/devel/api/mapping.html
--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #3
Daniel Cer wrote:
Why not just inherit from dict? That seems to work.
class M(dict): ... def __getitem__(sel f,key):
... return 42
... def __setitem__(sel f,key,value):
... pass
... class C(object): ... pass
... c = C()
c.__dict__ = M()
c.__dict__['x'] 42


Didn't test this very much, did you?
c.x
Traceback (most recent call last):
File "<pyshell#2 3>", line 1, in -toplevel-
c.x
AttributeError: 'C' object has no attribute 'x'

Or even:
c = C()
c.__dict__ = M({'x': 1})
c.x 1 c.__dict__['x'] 42


Jul 18 '05 #4
> > Why not just inherit from dict? That seems to work.

Because that isn't the question - Steven knows how to make it work, what he's
curious about is why things are the way they are :)
Sorry, didn't mean to be a pest :)

I guess I assumed Steve already knew that he could inherit from dict.
That being said, I was wondering why pragmatically this wouldn't be the
right thing to do (in order to do what he seemed to want to do).

<me> braces self for the true but not always too informative response of
'in principle, it's best to use the most abstract interface possible'</me>

-Dan


Anyway, a quick look suggests that it is due to typeobject.c using the concrete
PyDict_* API calls [1] to manipulate tp_dict, rather than the abstract
PyMapping_* calls [2]. The reason behind using the concrete API is, presumably,
a question of speed :)

Cheers,
Nick.

[1] http://www.python.org/dev/doc/devel/...ctObjects.html
[2] http://www.python.org/dev/doc/devel/api/mapping.html
--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list

Jul 18 '05 #5
Daniel Cer wrote:
Why not just inherit from dict? That seems to work.


Because that isn't the question - Steven knows how to make it work, what he's
curious about is why things are the way they are :)


Sorry, didn't mean to be a pest :)

I guess I assumed Steve already knew that he could inherit from dict.
That being said, I was wondering why pragmatically this wouldn't be the
right thing to do (in order to do what he seemed to want to do).


The problem with inheriting from dict is that you then need to override
*all* the methods in the dict object, because they all go straight to
Python's dict'c C code functions. So just because you redefine
__getitem__ doesn't mean you don't still have to redefine __contains__,
get, update, etc. UserDict.DictMi xin can help with this some, but the
ideal situation would be to only have to define the methods you actually
support. Inheriting from dict likely means you have to redefine a bunch
of functions to raise Exceptions saying that they're unsupported.

STeVe
Jul 18 '05 #6
Steven Bethard wrote:
The problem with inheriting from dict is that you then need to override
*all* the methods in the dict object, because they all go straight to
Python's dict'c C code functions. So just because you redefine
__getitem__ doesn't mean you don't still have to redefine __contains__,
get, update, etc. UserDict.DictMi xin can help with this some, but the
ideal situation would be to only have to define the methods you actually
support. Inheriting from dict likely means you have to redefine a bunch
of functions to raise Exceptions saying that they're unsupported.


You're just lucky the affected class is already overriding __getattribute_ _, so
the __dict__ is generally getting accessed from Python code :)

If it weren't for that, object.c's direct calls to the PyDict_* API would be
making things even more fun for you than they already are (as Duncan pointed out).

Cheers,
Nick.

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #7
Steven Bethard wrote:
support. Inheriting from dict likely means you have to redefine a bunch
of functions to raise Exceptions saying that they're unsupported.


Hmm. . .

We've got the NotImplemented singleton already to let special methods say "I
thought I might be able to handle this, but I can't".

Maybe "__op__ = NotImplemented" should clear the associated slot. It would also
make it easier to inherit from list and handle slices in __getitem__ by writing
"__getslice __ = NotImplemented" instead of overriding __getslice__ to delegate
to __getitem__.

Cheers,
Nick.

--
Nick Coghlan | nc******@email. com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.skystorm.net
Jul 18 '05 #8
Nick Coghlan wrote:
Steven Bethard wrote:
The problem with inheriting from dict is that you then need to
override *all* the methods in the dict object, because they all go
straight to Python's dict'c C code functions. So just because you
redefine __getitem__ doesn't mean you don't still have to redefine
__contains__, get, update, etc. UserDict.DictMi xin can help with this
some, but the ideal situation would be to only have to define the
methods you actually support. Inheriting from dict likely means you
have to redefine a bunch of functions to raise Exceptions saying that
they're unsupported.

You're just lucky the affected class is already overriding
__getattribute_ _, so the __dict__ is generally getting accessed from
Python code :)

If it weren't for that, object.c's direct calls to the PyDict_* API
would be making things even more fun for you than they already are (as
Duncan pointed out).


Yup, I noticed that. Lucky us. =)

STeVe
Jul 18 '05 #9

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

Similar topics

20
3300
by: Pierre Fortin | last post by:
Hi! "Python Essential Reference" - 2nd Ed, on P. 47 states that a string format can include "*" for a field width (no restrictions noted); yet... >>> "%*d" % (6,2) # works as expected ' 2' Now, with a mapping....
3
1503
by: Mauricio | last post by:
Hí! I´m implementing a web application using the Front Controller pattern described in the Enterprice Solutions Patters using Microsoft .NET v 1.0 In order to map an absolute path to another URL, an UrlMap class is implemented. This class implements the IConfigurationSectionHandler interface.
7
2917
by: Adam | last post by:
Im trying to add an httphandler for all *.sgf file extensions. I have developed the handler, 1. installed it into the gac 2. added it to the machine.config: <httpHandlers> <add verb="*" path="*.sgf" type="CustomExtensionHandler, Extenders.CustomExtensionHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d831d925597c1031" validate="True"/> </httpHandlers>
8
5039
by: Mike Kelly | last post by:
I've chosen to implement the "optimistic concurrency" model in my application. To assist in that, I've added a ROWVERSION (TIMESTAMP) column to my main tables. I read the value of the column in my select, remember it, and then use it in the update. It works just fine when I have full control of the whole process. I want to do the same for my GridView/SqlDataSource combinations. I typically select from a view and update the corresponding...
11
3561
by: JohnR | last post by:
I'm trying to find a way to create a variable of a given type at runtime where I won't know the type until it actually executes. For example, dim x as object = "hi" x is declared as an object but x.gettype returns 'string', so it knows it contains a string. If I want to create a variable "y" as the same type that variable x contains how would I do that without having to iterate thru every possible
8
1901
by: Steven D'Aprano | last post by:
I came across this unexpected behaviour of getattr for new style classes. Example: >>> class Parrot(object): .... thing = .... >>> getattr(Parrot, "thing") is Parrot.thing True >>> getattr(Parrot, "__dict__") is Parrot.__dict__ False
6
2244
by: Gaz | last post by:
Hi guys. I've been lookig for this in the numpy pdf manual, in this group and on google, but i could not get an answer... Is there a way to create a custom data type (eg: Name: string(30), Age: int(2), married: boolean, etc) and then use that custom data in a matrix? Actually, this is a two question question :P Im doing a simple hex based game and i need a way to store every hex property (color, owner,x, y, etc) in a matrix's "cell",...
16
1935
by: John Salerno | last post by:
Let's say I'm making a game and I have this base class: class Character(object): def __init__(self, name, stats): self.name = name self.strength = stats self.dexterity = stats self.intelligence = stats self.luck = stats
0
3466
by: Pieter | last post by:
Hi, I'm using NHibernate 1.2 (CR1), and I'm using a custom list (inherited from BindingList(Of T) ) for all my lists. The NHibernate documentation told me that I had to implement IUserCollectionType to my custom list, which I did. But I still get an error when trying to read the object: " {"Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag`1' to
0
8966
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
8786
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
9467
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
9331
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
9257
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
6749
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
4823
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3278
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
3
2192
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.