Missing interfaces in Python...

R

redefined.horizons

I'm coming from a Java background, so please don't stone me...

I see that Python is missing "interfaces". The concept of an interface
is a key to good programming design in Java, but I've read that they
aren't really necessary in Python. I am wondering what technique I can
use in Python to get the same benefits to a program design that I would
get with interfaces in Java.

For example, if I want to have a program with a Car object, and a Bus
object. I want both of these objects to present a common group of
methods that can be used by Mechanic objects, but slightly different
methods that can be used by Driver objects.

In Java I would accomplish this by defining an IFixable interface that
would be implemented by both the Car and Bus objects. Mechanic objects
would work with any object implementing this interface.

How would I approach this problem in Python? I think I would use an
abstract class instead of an interface for IFixable, since Python
supports multiple inheritance, but I'm not sure this is correct.

Thanks for any suggestions.

Scott Huey
 
S

Sybren Stuvel

(e-mail address removed) enlightened us with:
I see that Python is missing "interfaces".

No it isn't. It just hasn't got them.
The concept of an interface is a key to good programming design in
Java, but I've read that they aren't really necessary in Python.

In Java I would accomplish this by defining an IFixable interface
that would be implemented by both the Car and Bus objects. Mechanic
objects would work with any object implementing this interface.

In Python, you would simply call the functions you need. No need to
make things that rigidly defined.

Sybren
 
J

Jonathan Daugherty

# In Python, you would simply call the functions you need. No need to
# make things that rigidly defined.

Except when you need to handle exceptions when those methods don't
exist. I think interfaces can definitely be useful.
 
F

Fredrik Lundh

Jonathan Daugherty wrote_
# In Python, you would simply call the functions you need. No need to
# make things that rigidly defined.

Except when you need to handle exceptions when those methods don't
exist. I think interfaces can definitely be useful.

so with interfaces, missing methods will suddenly appear out of thin
air ?

</F>
 
E

Egon Frerich

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Have a look at Zope 3.
(http://www.zope.org/DevHome/Wikis/DevSite/Projects/ComponentArchitecture/FrontPage).
It has an interface implementation. You can use this implementation with
the apllication server Zope 3 or alone.

Regards,
Egon

I'm coming from a Java background, so please don't stone me...

I see that Python is missing "interfaces". The concept of an interface
is a key to good programming design in Java, but I've read that they
aren't really necessary in Python. I am wondering what technique I can
use in Python to get the same benefits to a program design that I would
get with interfaces in Java.

For example, if I want to have a program with a Car object, and a Bus
object. I want both of these objects to present a common group of
methods that can be used by Mechanic objects, but slightly different
methods that can be used by Driver objects.

In Java I would accomplish this by defining an IFixable interface that
would be implemented by both the Car and Bus objects. Mechanic objects
would work with any object implementing this interface.

How would I approach this problem in Python? I think I would use an
abstract class instead of an interface for IFixable, since Python
supports multiple inheritance, but I'm not sure this is correct.

Thanks for any suggestions.

Scott Huey

- --
Egon Frerich, Freudenbergstr. 16, 28213 Bremen

E-Mail: (e-mail address removed)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (MingW32)
Comment: GnuPT 2.7.2
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFERAsZuTzybIiyjvURAn4wAJ4qCaqAZu4BmnZzrltVAneyWwmh+wCeI8DV
DwNlvYJed/22Ls8Jct4fKV4=
=8eTo
-----END PGP SIGNATURE-----
 
I

I V

I see that Python is missing "interfaces". The concept of an interface
is a key to good programming design in Java, but I've read that they
aren't really necessary in Python. I am wondering what technique I can
use in Python to get the same benefits to a program design that I would
get with interfaces in Java.

To use interfaces in python, just what you would do in Java, except
don't use interfaces.

To expand on that slightly Zen answer, think about why you use
interfaces in Java. The interface declaration tells the compiler that
your object implements a specific set of functions, or that your
function expects an object that implements these functions. Then, at
run time, the actual type of the object is used to decide what function
to call.

However, python doesn't to any type checking at compile time, so it
just uses the dynamic type of the object to decide what function to
call.
How would I approach this problem in Python? I think I would use an
abstract class instead of an interface for IFixable, since Python
supports multiple inheritance, but I'm not sure this is correct.

Concretely:

class Car:
def fix(self):
print "Your car is ready, sir"


class Bus:
def fix(self):
print "Your bus is ready, sir"


class Mechanic:
def repair(self, customer, vehicle):
vehicle.fix()
customer.bill()


class Customer:
def bill(self):
print "Ouch, that was expensive"


me = Customer()
my_bus = Bus()
my_car = Car()
m = Mechanic()

m.repair(me, my_bus)
m.repair(me, my_car)

Which gives the output:

Your bus is ready, sir
Ouch, that was expensive
Your car is ready, sir
Ouch, that was expensive

If you try and repair something that can't be fixed:

m.repair(me, me)

you get:

Traceback (most recent call last):
File "test.py", line 30, in ?
m.repair(me, me)
File "test.py", line 14, in repair
vehicle.fix()
AttributeError: Customer instance has no attribute 'fix'

Obviously, you don't want this to happen when people use your program.
Java would check this at compile time, but as python doesn't, you can
write a unit test to check that the object's you want to implement the
relevant functions really do.

def is_fixable(obj):
try:
obj.fix
except AttributeError:
return False
return True

assert is_fixable(Car())
assert is_fixable(Bus())
assert not is_fixable(Customer())
assert not is_fixable(Mechanic())
 
L

Larry Bates

I'm coming from a Java background, so please don't stone me...

I see that Python is missing "interfaces". The concept of an interface
is a key to good programming design in Java, but I've read that they
aren't really necessary in Python. I am wondering what technique I can
use in Python to get the same benefits to a program design that I would
get with interfaces in Java.

For example, if I want to have a program with a Car object, and a Bus
object. I want both of these objects to present a common group of
methods that can be used by Mechanic objects, but slightly different
methods that can be used by Driver objects.

In Java I would accomplish this by defining an IFixable interface that
would be implemented by both the Car and Bus objects. Mechanic objects
would work with any object implementing this interface.

How would I approach this problem in Python? I think I would use an
abstract class instead of an interface for IFixable, since Python
supports multiple inheritance, but I'm not sure this is correct.

Thanks for any suggestions.

Scott Huey
Just thought I'd put in my 2 cents. You may want to take a look at
Zope 3 (www.zope.com). If I understand what you ware looking for, I
think they have already solved the problem (at least in one way). It
is at least worth a quick review.

You will find that most Python programmers bristle at words like
"missing", "enforcement" and "strictly defined the type". Python
programmers just don't work that way. The fact that programmers in
other languages must, is their loss.

-Larry Bates
 
I

I V

Jonathan said:
Except when you need to handle exceptions when those methods don't
exist. I think interfaces can definitely be useful.

I think I see what you mean, but that's an odd way to put it.
Typically, you aren't going to handle the exceptions produced by type
errors. Of course, you want some way to test that your code doesn't
have type errors. Static type checking is one way of doing the
requisite testing, unit tests are another, but it's the tests that are
useful, not the interfaces per se. Adding interfaces to python, which
doesn't support static type checking, would be useless IMO.
 
R

Roy Smith

I see that Python is missing "interfaces". The concept of an interface
is a key to good programming design in Java, but I've read that they
aren't really necessary in Python. I am wondering what technique I can
use in Python to get the same benefits to a program design that I would
get with interfaces in Java.

Python is a very dynamic language. Java is a very static language.
What that means is that in Java (like C++), you do a lot of error
checking at compile time. That's what interfaces are all about. In
Python, you do almost no error checking (beyond basic language syntax)
at compile time, and do everything at run time. For the most part,
this means wrapping things in try blocks and catching exceptions.
For example, if I want to have a program with a Car object, and a Bus
object. I want both of these objects to present a common group of
methods that can be used by Mechanic objects, but slightly different
methods that can be used by Driver objects.

In Java I would accomplish this by defining an IFixable interface that
would be implemented by both the Car and Bus objects. Mechanic objects
would work with any object implementing this interface.

How would I approach this problem in Python? I think I would use an
abstract class instead of an interface for IFixable, since Python
supports multiple inheritance, but I'm not sure this is correct.

Well, let's say your IFixable interface in Java would have included
changeTire(), rechargeBattery(), and adjustBrakes() methods. In
Python, I'd just go ahead and implement those methods for both Car and
Bus classes. All Java's interface mechanism does for you is provide
some compile-time checking that those methods are implemented. In
Python, you would just call those methods when appropriate, and catch
any NameError exception that would happen if it turns out there is no
such method.

Consider that in Python, an object can have methods added to it after
it is created. It's entirely possible that the Car class has no
changeTire() method, but one would be added to each Car instance
sometime before the first place it might be called. Consider
something like:

if self.owner.hasRoadsideAssistance():
self.changeTire = callForHelp
elif self.owner.canFixThings:
self.changeTire = getHandsDirty

Now, calling myCar.changeTire() could end up calling callForHelp(), or
calling getHandsDirty(), or throwing NameError is no way exists to get
the tire fixed. Maybe that's what makes sense in your application.
 
T

Terry Reedy

I'm coming from a Java background, so please don't stone me...

Most of us came to Python from some other language background ;-)
I see that Python is missing "interfaces".

As someone else noted, Python objectively does not have 'interfaces' (or
'protocols') as an object type in the language. (But 'missing' is somewhat
subjective.) On the other hand, the concepts are very much part of the
language. See the article on duck typing, which could be called duck
interfacing, that someone gave a link for.

For example, an iterator (newer definition) is an object with an __iter__()
method returning self and a next() method that returns objects until it
raises StopIteration. An iterable is an object with an __iter__() method
that return an iterator. (Hence, iterators are conveniently iterables
also.) Instead of declaring that a class implements IterableInterface, you
just implement it (and the corresponding iterator class if needed) and use
it anywhere an iterable is expected, which is lots places in the builtins
and standard library.
How would I approach this problem in Python? I think I would use an
abstract class instead of an interface for IFixable, since Python
supports multiple inheritance, but I'm not sure this is correct.

I believe this
<class exceptions.NotImplementedError at 0x00974810>

was added so that people could go the route of abstract base classes with
stub functions.

Terry Jan Reedy
 
A

Alex Martelli

Jonathan Daugherty said:
# enforced by whom, at what point ?

In the case of Java, I think the JVM enforces interface implementation
(probably at the parser level).

"parser"...?! If you have an 'Object o', say one just received as an
argument, and cast it to IBlahble, a la

IBlahble blah = (IBlahble) o;

....what can the parser ever say about it? It's clearly up to the
runtime system to "enforce" whatever -- raising the appropriate
exception if the "actual" (leafmost) class of o does not in fact
implement IBlahble (Java doesn't _really_ do compile-time static typing:
it just forces you to violate the "Don't Repeat Yourself" cardinal rule
by redundantly repeating types, as above, but then in general it checks
things at runtime anyway!).


Alex
 
J

Jonathan Daugherty

# "parser"...?! If you have an 'Object o', say one just received as an
# argument, and cast it to IBlahble, a la
#
# IBlahble blah = (IBlahble) o;
#
# ...what can the parser ever say about it?

Maybe you didn't read the "I think" in my OP. Anyway, you clearly
know more about (or have more recent experience with) Java than I do.
 
A

Alex Martelli

Jonathan Daugherty said:
# "parser"...?! If you have an 'Object o', say one just received as an
# argument, and cast it to IBlahble, a la
#
# IBlahble blah = (IBlahble) o;
#
# ...what can the parser ever say about it?

Maybe you didn't read the "I think" in my OP. Anyway, you clearly
know more about (or have more recent experience with) Java than I do.

My real-world experience with Java is very dated -- nowadays, I'm told,
the NEED to cast is vastly reduced by Java 1.5's "generics" (I haven't
yet written one line of Java 1.5, not even for "play" purposes, much
less "real world" ones;-). Still, all the casting that used to work
still works, so the purported "compile-time type safety" is worth as
much as the social compact to "don't use any of the container classes
that used to work until 1.4.*, but ONLY the very newest ones in 1.5"!-)
So much for "compiler enforcement", hm?-)


Alex
 
J

Jonathan Daugherty

# My real-world experience with Java is very dated -- nowadays, I'm
# told, the NEED to cast is vastly reduced by Java 1.5's "generics" (I
# haven't yet written one line of Java 1.5, not even for "play"
# purposes, much less "real world" ones;-).

Interesting; thanks.

# So much for "compiler enforcement", hm?-)

Yes, indeed. :)
 
G

gmilas

I am currently working in C# after I spent about 3 years almost only in
python, The way I see thinks is that for me we need interfaces in C# to
allow for flexibility in using OOP because we must only pass defined
and known types at all times so for us to have the flexibility of
passing either a Car or a Bus to the Mechanic when we actually only
need their fixIt method we need to use a common type that will
accommodate the constraint of having the fixIt method. Of course this
could also be implemented using an abstract base class but since in C#
as well as in Java we don't have multiple inheritance it is better to
use an interface for flexibility purpose (for ex. sometime you have to
subclass from MarshalByRefObject in order to use the object in a
distributed system so inheritance is out of the question as a means to
flexibility in that case).

So for good and flexible OOP in C# someone should use interfaces
because it is the only way to achive the flexibility needed but in
python because of duck typing you always get the flexibility without
you doing anything special like trying to come up with a type that
accommodates some common ground of other types, so as someone say here
"To use interfaces in python, just do what you would do in Java, except
don't use interfaces."

So to digress a little, for me the difference is that in C# you are
given safety, documentation (read app. domain definitions) and
track-ability (read refactoring, intelisense) but you have to code for
flexibility while in python you are given flexibility but you have to
code for safety and documentation and as far as for track-ability you
are usually out of luck. Now many people agree that the safety you are
given in C# is usually far from ideal (no app. domain logic safety
given) so usually you have to code for that as well as in python, and
my opinion is that the documentation provided by type definition wile
ok, for best maintainability you have to provide comments anyway about
their app. domain means just like you do in python, so the only think
that is different is that the lack of track-ability in python is
sometime annoying for me now when I'm going back to python after a
little bit of C#, but the annoyance is even bigger when in C# I always
have to think ahead of time how to make sure that my code if flexible
enough to support easy changing.

Gheorghe Milas
 
O

olsongt

I'm coming from a Java background, so please don't stone me...

I see that Python is missing "interfaces". The concept of an interface
is a key to good programming design in Java, but I've read that they
aren't really necessary in Python. I am wondering what technique I can
use in Python to get the same benefits to a program design that I would
get with interfaces in Java.

For example, if I want to have a program with a Car object, and a Bus
object. I want both of these objects to present a common group of
methods that can be used by Mechanic objects, but slightly different
methods that can be used by Driver objects.

In Java I would accomplish this by defining an IFixable interface that
would be implemented by both the Car and Bus objects. Mechanic objects
would work with any object implementing this interface.

How would I approach this problem in Python? I think I would use an
abstract class instead of an interface for IFixable, since Python
supports multiple inheritance, but I'm not sure this is correct.

Thanks for any suggestions.

Scott Huey

Everyone is getting off track here.

Java has interfaces because it doesn't support multiple inheritance.
Python supports MI, so you don't need to use the seperate concept of an
interface. You're right that an abstract class is the equivilent of an
interface. Just create a ABC that raises NotImplementedExceptions for
each of the methods, and use that class as one of the base classes. Of
course, like a lot of stuff in python, this won't throw an exception at
'compile-time', only when you try to invoke a method that has no
implemenation.

The general wisdom is that Abstract Base Classes aren't pythonic
though. If you want to be pythonic, just implement the methods for
your 'interface', and (if necessary) check for their existance with
hasattr before calling (or even just call the method and you'll get an
attribute error anyway). This is referred to as duck-typing. If it
looks like a duck, and quacks like a duck, then for all practical
purposes it supports the 'duck' interface.
 
P

Peter Maas

Fredrik said:
Jonathan Daugherty wrote_


so with interfaces, missing methods will suddenly appear out of thin
air ?

He probably means that with interfaces one could test compliance with
the interface as a whole instead of testing each member and each
signature as a single piece.

Peter Maas, Aachen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top