Saturday, January 08, 2005

Re: Advice for Computer Science College Students

I did read up a bit on Python. What I got was a lot on the libraries. Could Mohn post a small example of creating a simple Class.

Here are two simple programs which we had as projects. They are reasonably documented so you shouldn't have a problem figuring them out.

This first one is quite simple. It sends a request to a domain name and outputs what server (IIS, Apache, Unix etc...) the site is hosted on. The Java version is almost exactly the same.

from sys import argv
from httplib import HTTPConnection
from httplib import InvalidURL

# -------------------
# printHTTPServerInfo
# -------------------

# Prints the name of the web server the specified URL is hosted on
# url - url of website
def printHTTPServerInfo( url ):
    try:
        connection = HTTPConnection( url )

        try:
            connection.request( "GET", "/" )

            response = connection.getresponse()

            server = response.getheader( "Server" )

            if server == None:
                print "Could not detect what server \"%s\" is hosted on" % url
            else:
                print "\"%s\" is hosted on %s" % (url, server)
        finally:
            connection.close()
        except InvalidURL, ex:
            print "\t--> Not a valid url. Expected format: 'www.hostname.com'"
            print "\t--> %s" % ex
    except Exception, ex:
        print "\t--> An error occured"
        print "\t--> %s" % ex


# Application entry point
if len( argv ) != 2:
    print "Usage: GetHTTPServerInfo "
    print " where is in the format 'www.hostname.com'"
else:
    printHTTPServerInfo( argv[ 1 ] )


The next one is a bit to do with AOP concepts. I had posted something a while back and gave an example using Java. This is more or less something similar. But in this case, you can optionally inject your own functions before and after the method call. One thing to notice is that Python makes it very easy (much more so than Java etc...) to add "dynamic" functions to a class - ie. functions that you don't define when writing the class. If you're interested I can post an explanation for what's happening.

# -----
# Proxy
# -----

class Proxy:
    """
    Intercepts all the method calls to some other class instance, delegating to the same method of the "proxied" class.
    In addition, it allows the user to specify functions that should be invoked before/after the delegation call.
    """

    # --------
    # __init__
    # --------

    def __init__( self, delegate_instance, before = None, after_ok = None, after_exception = None ):
        """
        Initializes a new Proxy object
        params:
        delegate_instance - the object to delegate method calls to
        before - the method to run before calling the called method
        after_ok - the method to run after calling the called method if it is a success
        after_exception - the method to run after calling the called method if it is a failure
        """

        self.delegate = delegate_instance
        self.beforeMethod = before
        self.afterMethodSuccess = after_ok
        self.afterMethodFailure = after_exception

    # -----------
    # __getattr__
    # -----------

    def __getattr__( self, name ):
        """
        Intercepts the specified method call
        params:
        name - the name of the method called
        returns:
        the invocation handler
        """

        self.methodName = name

        return self.InvocationHandler

    # -----------------
    # InvocationHandler
    # -----------------

    def InvocationHandler( self, *args, **kwargs ):
        """
        Invokes called method and any specified methods before and after method call
        params:
        *args - the positional arguments to pass to called method
        **kwargs - the named arguments to pass to called method
        """

        method = getattr( self.delegate, self.methodName )

        if self.beforeMethod != None:
            self.beforeMethod( method, *args, **kwargs )

        try:
            result = method( *args, **kwargs )

            if self.afterMethodSuccess != None:
                self.afterMethodSuccess( method, result, *args, **kwargs )

            return result
        except Exception, ex:
            if self.afterMethodFailure != None:
                self.afterMethodFailure( method, *args, **kwargs )

            raise ex


About size of projects, an application server Zope has been created in Python. So that kind of sets a very high limit for the size of Python projects.

Python is definitely being used for many large and diverse projects. BBC has a project where they plan to put their entire TV and radio archives online. They are using Python to develop some new networking protocols because apparently the current ones won't be able to handle the load.

Python has also got a Java port called Jython. So any code written in Python is converted to Java .class files. The author of the book also mentioned that a .NET python version may be released some day.

Ya I've heard about Jython and the .NET version (IronPython), but never looked at either one. Does Jython just produce Java bytecodes and thats it or can you also use the Java API? I would think that the whole point would be to enable using the libraries since Python already has a lot of features that the JVM/CLR provides - garbage collection, exception management etc... And what dyou think of these ports? Dyou think they are useful?

The python GUI library also uses Tcl/Tk in some way.

What is Tcl/Tk? How is the Python GUI library using it?

The next module is on Databases, queries and internals. What stuff do you guys know on the topic. So far the most complicated queries I have ever tried are "SELECT * FROM MYTABLE"!!

Not a lot. Just the basic SELECT, INSERT, UPDATE, DELETE stuff and a bit on Stored Procs (not writing them, just using them). So good topic to post stuff on!

We should have a discussion on the How MS lost the API war blog which Mohn linked to. What did you guys think of it?

I read it when he posted it, so its been a while. I'll go over it again and post my thoughts. Why don't you start? And Hrishi, Dinesh and Nikhil - we'd love to read your 2 cents too.

No comments: