473,804 Members | 3,156 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

__contains__ vs. __getitem__

I have a subclass of dict where __getitem__ returns None rather than
raising KeyError for missing keys. (The why of that is not important for
this question.)

I was delighted to find that __contains__ still works as before
after overriding __getitem__. So even though instance['key']
does not raise KeyError, I still get (as desired) 'key' in instance ==
False.

Looking forward:
Can I count on this independence of __getitem__ and __contains__?
I would like to understand whether it will be safe to count on this
behavior.

Thank you,
Alan Isaac
Aug 9 '06 #1
7 2336
David Isaac wrote:
I have a subclass of dict where __getitem__ returns None rather than
raising KeyError for missing keys. (The why of that is not important for
this question.)
Well, actually it may be important... What's so wrong with d.get('key')
that you need this behaviour ?

Aug 9 '06 #2
That's a vague question, so the obligatory "it depends" response
applies here.

If you want to guard against the unexpected, perhaps it's a good idea
to write unit tests rather than to take someone's word that it *should*
work okay every time, in every case, no matter what you're doing with
the data. Think of what behavior would be disasterous (whether it seems
possible or not), then write a test for that behavior. Also write tests
for things that "obviously" *should* hold true... just to make sure
they hold true.

Maybe you can't think of ways that this class could possibly screw
things up, but it's always nice to have reassurance anyway :-) The
closest thing to certainty about code is to test it.

David Isaac wrote:
I have a subclass of dict where __getitem__ returns None rather than
raising KeyError for missing keys. (The why of that is not important for
this question.)

I was delighted to find that __contains__ still works as before
after overriding __getitem__. So even though instance['key']
does not raise KeyError, I still get (as desired) 'key' in instance ==
False.

Looking forward:
Can I count on this independence of __getitem__ and __contains__?
I would like to understand whether it will be safe to count on this
behavior.

Thank you,
Alan Isaac
Aug 9 '06 #3
Alan Isaac wrote:
I have a subclass of dict where __getitem__ returns None rather than
raising KeyError for missing keys. (The why of that is not important
for
this question.)
"Bruno Desthuilliers" <on***@xiludom. growrote:
Well, actually it may be important... What's so wrong with d.get('key')
that you need this behaviour ?
I want to use the mapping with string interpolation.

Alan Isaac
Aug 9 '06 #4
On Wed, 09 Aug 2006 16:51:23 GMT
"David Isaac" <ai*****@verizo n.netwrote:
Looking forward:
Can I count on this independence of __getitem__ and __contains__?
I would like to understand whether it will be safe to count on this
behavior.

With the builtin 'dict' implementation, dict.__contains __() use the
dict_has_key() C function, and does not touch your subclass __getitem__
python method. I don't think it can be called 'safe'... it may lead to
very inconsistent behavior. It's like overridind both __eq__ and __ge__
with a different behavior. It's better for you to override
__contains__() too.
--
Pedro Werneck
Aug 9 '06 #5
David Isaac wrote:
>Alan Isaac wrote:
>>I have a subclass of dict where __getitem__ returns None rather than
raising KeyError for missing keys. (The why of that is not important
for
>>this question.)

"Bruno Desthuilliers" <on***@xiludom. growrote:
>Well, actually it may be important... What's so wrong with d.get('key')
that you need this behaviour ?

I want to use the mapping with string interpolation.
Well, this makes sens... But then why not use a plain dict to collect
data, and wrap it in a special one just before using it for
interpolation ? ie:

class MyDictWrapper(o bject):
def __init__(self, d, default=None):
self._d = d
self._default = default
def __getitem__(sel f, key):
return self._d.get(key , self._default)
def render(d):
tpl = "%(who)s says '%(say)s' and the %(what)s is %(state)s."
return tpl % MyDictWrapper(d )

This would avoid any potential trouble with using a strange kind of dict
in other parts of the code...

My 2 cents...
Aug 10 '06 #6
Pedro Werneck <pe***********@ terra.com.brwro te:
On Wed, 09 Aug 2006 16:51:23 GMT
"David Isaac" <ai*****@verizo n.netwrote:
Looking forward:
Can I count on this independence of __getitem__ and __contains__?
I would like to understand whether it will be safe to count on this
behavior.

With the builtin 'dict' implementation, dict.__contains __() use the
dict_has_key() C function, and does not touch your subclass __getitem__
python method. I don't think it can be called 'safe'... it may lead to
very inconsistent behavior. It's like overridind both __eq__ and __ge__
with a different behavior. It's better for you to override
__contains__() too.
I think it's perfectly safe -- that's what defaultdict in Python 2.5
does, after all.
Alex
Aug 11 '06 #7
Bruno Desthuilliers <on***@xiludom. growrote:
David Isaac wrote:
Alan Isaac wrote:
I have a subclass of dict where __getitem__ returns None rather than
raising KeyError for missing keys. (The why of that is not important
for
>this question.)
"Bruno Desthuilliers" <on***@xiludom. growrote:
Well, actually it may be important... What's so wrong with d.get('key')
that you need this behaviour ?
I want to use the mapping with string interpolation.
Well, this makes sens... But then why not use a plain dict to collect
data, and wrap it in a special one just before using it for
interpolation ? ie:
Using a single container (and being able to modify and use it fluidly)
is simply handier. That's what defaultdict in Python 2.5 is for, btw.
Alex
Aug 11 '06 #8

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

Similar topics

4
8026
by: KanZen | last post by:
I'm trying to understand the difference between __setitem__ and an ordinary method. For example: >>> class A(object): def __getitem__(self, *args): print len(args) def normalMethod(self, *args): print len(args) >>> a=A()
1
4578
by: Skip Montanaro | last post by:
I got to wondering if there is a difference between __contains__() and has_key() for dictionaries (I don't think there is), so I peeked at UserDict.UserDict and saw they were implemented as distinct methods: def has_key(self, key): return self.data.has_key(key) def __contains__(self, key): return key in self.data
2
1696
by: Anand S Bisen | last post by:
Hello I have been developing a code that works pretty well on my python 2.3 and now when i am running it on my server where it is programmed to run it's giving me errors. I have been using __contains__ method and it fails on python 2.2 For example (Python 2.3)
3
5959
by: Tobiah | last post by:
#!/usr/bin/python # Hi, # # I noticed something interesting when trying to define # the __getitem__() method in a class that inherits from # (dict). If within the __getitem__ method I attempt # to get an item from self, the __getitem__ method is # called in an infinite recursion. I am very fond of # inheriting from (dict) as in the class 'bar' below,
1
1986
by: simon | last post by:
What i'm trying to do is tie special methods of a "proxy" instance to another instance: def test1(): class Container: def __init__( self, data ): self.data = data self.__getitem__ = self.data.__getitem__ data = range(10)
21
3587
by: ron | last post by:
Why doesn't this work? >>> def foo(lst): .... class baz(object): .... def __getitem__(cls, idx): return cls.lst .... __getitem__=classmethod(__getitem__) .... baz.lst = lst .... return baz .... >>> f = foo()
5
1515
by: rconradharris | last post by:
A co-worker of mine came across some interesting behavior in the Python interpreter today and I'm hoping someone more knowledgeable in Python internals can explain this to me. First, we create an instance of an Old-Style class without defining a __contains__ but instead define a __getitem__ method in which we raise KeyError. Next we repeatedly use the 'in' operator to test to see whether something, a string, an int, etc is an attribute...
3
1540
by: sebastien.lannez | last post by:
Hi everybody, I need to overload the operator in and let him return an object ... It seems it is not a behavior Python expect : .... def __contains__(self,a): .... return 'yop' .... True
3
2038
by: sebastien.lannez | last post by:
Thanks for your quick response. Using Python as an algebraic parser for symbolic mathematical equation and I need that the 'in' operator returns an object based on its two arguments.
0
10571
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
10326
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...
0
10075
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...
1
7615
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
6851
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5520
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...
1
4295
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
3815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2990
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.