[Tutor] intefaces in python

Luke Paireepinart rabidpoobear at gmail.com
Mon Jun 29 14:28:26 CEST 2009

Amit Sethi wrote:
> I think ideally i want a compile Error just like java ..
Why?  For developers, so they'll know if their plugin meets the 
interface requirements?
Have you considered just making a unit test that will call all interface 
functions with appropriate parameters?  Then they can just run the test 
on their code and if it passes they will know they implemented the 
minimum required functions (whether they do what they're supposed to do 
is a different story...)  It would provide the same level of interface 
security as Java would, except it would allow them to decide how much of 
the contract they need to enforce for their specific application. That's 
one of the things I like about python... for example, if I want to 
override stdout so all my print statements go to a file, I just have to 
create a new class that has a write() method that writes anything it's 
passed to a file... I don't have to implement all of the other 
functionality that whatever object resides there before has.  So in that 
case, if I ran your unit test on my replacement stdout, it may say "Hey, 
you failed the writeline() test, your object doesn't have this!" but 
since I know I'm not going to use writeline, I can just ignore the 
warning.  Or if I meant for it to have writeline, I can say "oh snap I 
need to go implement writeline!"  But as I said, that wouldn't enforce 
the interface, just inform them of it if they desired that, which I 
would personally prefer but you may not.
That's really the idea behind duck typing.  Assume that they wrote 
sufficient code to handle whatever you use it for and if they didn't 
it'll blow up in their face.
> @Dave Angel
> You have said
> "you could arrange that when the plugin is first encountered, you
> validate that it has all the required methods and data members.  Not
> by calling them, but by scanning the object for their existence."
> that would be ideal ... can you enlighten me on this how may one do that.
Not sure if it's what he meant, but you can just do a dir(object) and it 
will return a list with all method / member names.  then you could just 
confirm that the names are there.

More information about the Tutor mailing list