Checking if a variable is a dictionary

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Mar 9 14:13:48 CET 2008


On Sun, 09 Mar 2008 05:20:41 -0700, Guillermo wrote:

>>A protocol is just an interface that an object agrees to implement. In
>>your case, you would state that every object stored in your special dict
>>must implement the to_tagged_value method with certain agreeable
>>semantics.
> 
> Hm... I've searched about the implementation of protocols and now (I
> believe) I know how to implement the iterable protocol, for instance,
> but have no clue about how to define my own... I'm surely not thinking
> the right way, but I don't seem to be able to wrap my head around the
> implementation details of "custom" protocols... Is it just a matter of
> extending the different object classes (dict, list, tuple...)? Where do
> you put the interface/protocol code? :-?


A protocol is a convention that you insist other objects must follow, not 
code. To implement that convention, naturally you need to write code, but 
the convention makes the protocol, not the code.

Some examples:

To be considered a writable file, your object must include a write() 
method and a close() method. It doesn't matter what those methods do 
exactly, so long as they behave reasonably. For instance, the close() 
method might do nothing, and the write() method might send an SMS.

To be a random-access writable file, it must also include a seek() method.

To be a sequence, your object must obey the sequence protocol, which says 
it has a __getitem__ method which takes integer arguments starting at 0 
and increasing, until it raises IndexError.

You don't have to write any code to create a protocol, you just have to 
tell people what it is. Here's my parrot protocol:


To be a parrot, your object must have a method speak() which takes an 
integer argument and returns the case-insensitive string "spam" repeated 
that many times.


I'm done. I have a protocol. But if I want to actually use it, then I 
need an object that obeys it, and if I can't wait for somebody else to 
write it, I need to write one myself. So here it is:

class Viking(object):
    def __init__(self, case='upper'):
        if case == 'upper':
            self.case = str.upper
        else:
            self.case = str.lower
    def speak(self, n):
        return self.case("spam"*n)


And now Viking instances are also parrots, or rather, they obey the 
parrot protocol:

>>> v = Viking()
>>> v.speak(3)
'SPAMSPAMSPAM'


I hope this helps.


-- 
Steven



More information about the Python-list mailing list