Missing interfaces in Python...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • redefined.horizons@gmail.com

    #1

    Missing interfaces in Python...

    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

  • Sybren Stuvel

    #2
    Re: Missing interfaces in Python...

    redefined.horiz ons@gmail.com enlightened us with:[color=blue]
    > I see that Python is missing "interfaces ".[/color]

    No it isn't. It just hasn't got them.
    [color=blue]
    > 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.[/color]

    [color=blue]
    > 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.[/color]

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

    Sybren
    --
    The problem with the world is stupidity. Not saying there should be a
    capital punishment for stupidity, but why don't we just take the
    safety labels off of everything and let the problem solve itself?
    Frank Zappa

    Comment

    • Jonathan Daugherty

      #3
      Re: Missing interfaces in Python...

      # 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.

      --
      Jonathan Daugherty

      Comment

      • Fredrik Lundh

        #4
        Re: Missing interfaces in Python...

        Jonathan Daugherty wrote_
        [color=blue]
        > # 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.[/color]

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

        </F>



        Comment

        • Egon Frerich

          #5
          Re: Missing interfaces in Python...

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

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

          Regards,
          Egon

          redefined.horiz ons@gmail.com schrieb am 17.04.2006 22:39:
          [color=blue]
          > 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
          >[/color]

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

          E-Mail: e.frerich@nord-com.net
          -----BEGIN PGP SIGNATURE-----
          Version: GnuPG v1.4.2.2 (MingW32)
          Comment: GnuPT 2.7.2
          Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

          iD8DBQFERAsZuTz ybIiyjvURAn4wAJ 4qCaqAZu4BmnZzr ltVAneyWwmh+wCe I8DV
          DwNlvYJed/22Ls8Jct4fKV4=
          =8eTo
          -----END PGP SIGNATURE-----

          Comment

          • I V

            #6
            Re: Missing interfaces in Python...


            redefined.horiz ons@gmail.com wrote:[color=blue]
            > 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.[/color]

            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.
            [color=blue]
            > 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.[/color]

            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(Cust omer())
            assert not is_fixable(Mech anic())

            Comment

            • Larry Bates

              #7
              Re: Missing interfaces in Python...

              redefined.horiz ons@gmail.com wrote:[color=blue]
              > 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
              >[/color]
              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", "enforcemen t" 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

              Comment

              • I V

                #8
                Re: Missing interfaces in Python...

                Jonathan Daugherty wrote:[color=blue]
                > Except when you need to handle exceptions when those methods don't
                > exist. I think interfaces can definitely be useful.[/color]

                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.

                Comment

                • Roy Smith

                  #9
                  Re: Missing interfaces in Python...

                  <redefined.hori zons@gmail.com> wrote:[color=blue]
                  > 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.[/color]

                  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.
                  [color=blue]
                  >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.[/color]

                  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.hasR oadsideAssistan ce():
                  self.changeTire = callForHelp
                  elif self.owner.canF ixThings:
                  self.changeTire = getHandsDirty

                  Now, calling myCar.changeTir e() 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.

                  Comment

                  • Terry Reedy

                    #10
                    Re: Missing interfaces in Python...


                    <redefined.hori zons@gmail.com> wrote in message
                    news:1145306373 .781129.305840@ z34g2000cwc.goo glegroups.com.. .[color=blue]
                    > I'm coming from a Java background, so please don't stone me...[/color]

                    Most of us came to Python from some other language background ;-)
                    [color=blue]
                    > I see that Python is missing "interfaces ".[/color]

                    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 IterableInterfa ce, 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.
                    [color=blue]
                    > 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.[/color]

                    I believe this
                    [color=blue][color=green][color=darkred]
                    >>> NotImplementedE rror[/color][/color][/color]
                    <class exceptions.NotI mplementedError at 0x00974810>

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

                    Terry Jan Reedy



                    Comment

                    • Alex Martelli

                      #11
                      Re: Missing interfaces in Python...

                      Jonathan Daugherty <cygnus@cprogra mmer.org> wrote:
                      [color=blue]
                      > # enforced by whom, at what point ?
                      >
                      > In the case of Java, I think the JVM enforces interface implementation
                      > (probably at the parser level).[/color]

                      "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

                      Comment

                      • Jonathan Daugherty

                        #12
                        Re: Missing interfaces in Python...

                        # "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.

                        --
                        Jonathan Daugherty

                        Comment

                        • Alex Martelli

                          #13
                          Re: Missing interfaces in Python...

                          Jonathan Daugherty <cygnus@cprogra mmer.org> wrote:
                          [color=blue]
                          > # "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.[/color]

                          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

                          Comment

                          • Jonathan Daugherty

                            #14
                            Re: Missing interfaces in Python...

                            # 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. :)

                            --
                            Jonathan Daugherty

                            Comment

                            • Pablo Orduña

                              #15
                              Re: Missing interfaces in Python...

                              This article in Guido van Rossum's blog might be interesting for this
                              thread



                              --
                              Pablo

                              Comment

                              Working...