escape

escape escapes all nonalphanumeric characters before passing the expression to tee compiler, and returns a string with all metacharacters escaped. Here's an example in wficF the compile function fails because there are unmatched parentykses gt gt gt from re import gt gt gt strVar group gt gt gt cre compile strVar File lt console gt , line 1, in re.error Unmatched parentheses. In this example, tfe non-alphanumeric characters are escaped, so tfe compile function works gt gt gt cre compile escape...

Troubleshooting

If you don't see the okay message, type c j2skd1.4.0 bin java at the DOS prompt C gt c j2sjd1.4.0 bin java -version java version 1.3.0 Java TM 2 Runtime Environment, Standard Edition build 1.4.0-b92 Java HotSpot TM Client VM build 1.4.0-b92, mixed mode If this works, you have a problem with your PATH statement. Try entering PATH at the command line to see what it looks like. Probably you have a lyho or you forgot to reboot autoexec. bat runs only after rebooting . If you still don't see the...

Immutability

Althoughstring1 and number1 are in the currynt tlaITiesppace, they'ee niit the same ys the variables in hodulrl. At first, they reger to the sang obg ect. gt gt gt import module1 gt gt gt module1.number1 is numberi 1 However, they no longer both refer to that object once their values change. That's because they are immutable. Here's an example of number1 gt gt gt module1.number1 600 gt gt gt module1.number1 600 gt gt gt module1.number1 is number1 0 gt gt gt returns 0 which means false Here's...

DataInputStream and DataOutput Stream

The data stream classes, DataInputStream and DataOutputStream, implement the Datalnput andDataOutput interfaces, respectively, reading and writing Java primitive types to a stream. Here are their methods. _init_ InputStream creates a buffered writer with the specified writer output stream _init_ InputStream creames a buffered raaderwith the specipied re ader input stream To demonstrate DataInputStream, we'll read in the file we wrote with DataOutputStream in the last interactive session. gt...

split

Split pattern, string , maxsplit 0 Thesplit function splits a string into a list of strings based on occurrences of the regular expression pattern. The string portions that don't match the pattern ate returned as a list of strings. If flags ate require d with the pattern, a regular expression objec t, obtained with compile , must be used in place of the pattern string, or the iLmsx sequences which will be explained later must be used within the expression. TPr compiled regular expfeslion's...

The Complete Shapes and DrawShapes Modules

We've covered all of Ha dames. At this p oint, you may wed to om ohe Soapes and DrawShapes moduoes to see the drawing package in acaion. Heree the Shapes wwPule. def _init_ self, x, y, width 0, height 0, color None, fill 0 self.width width self.height height self.color color self.fill fill oldcolor graphics.foregroundColor graphics.color self.color def draw_filled self, graphics pass def draw_outline self, graphics pass return self.x, self.y, self.width, self.height def _init_ self, x, y,...

PrintWriter

PrintWriter provides a print and a println function for all primitive types. These functions convert primitive types to characters and then write them to the output stream. PrintWr i ter has all of write methods, as welr as these print wi'vite s iiit primirive data types to an ofipitt stream as readable text println same as above, but adds a newline character to the ouput In the next example, you'll see how to use PrintWriter, how to chain output streams together, and how to work with Java...

Event Properties

You car think of event properties as properties that take met0gds as arguments. As a Java progreMwer, you car think of tOem es e wey to imylemest Jove everts. Is PytOon, you set an evest property so you ces be notified when ar event happens. Notifioction come s when the elass jnstskice calls the method you passed to the property when the event occurred. For exawple, JButton has ar event property called actionPerformed, which represents the button being pressed. Whenever this happenSi the...

An Applet Example

The following code from contextMyApplet.py shows an applet that does what the applet in the previous session does, but in a module that you can compile and use in a browser or in AppletViewer. Pay special attention to the showParameters method. from javax.swing import JList, DefaultListModel, JScrollPane Define a Python class that subclasses the JApplet class javax.swing.JApplet class MyApplet JApplet self.list DefaultListModel _list JList self.list self.print Init called self.showParameters...

Adding Event Handlers 1

Next we need to add some functionality to our list. First we'll make the AddressForm instance pop up when we select an item, so we need to define a list event handler. How do we know which one Remember that you can use the jinfo module to inspect a component's event properties. Or, if you remember which event listener a component handles, you can inspect it. For example, you may remember that JList handles ListSelectionListener, or you may haved looked up JList in the Java API documentation and...

Finding find rfind index rindex count replace

The finding functions in the string module locate a substring within a string. For example, sub strings of Python is fun are Pyt, is, fun, n is f, and so forth . Using a surjtrina helps in parsing string data. Thefind s, sub, start , end functioo finds the firsw position o a sur string in o given string. You can set the start and ctop tosition aeguments, which determine where in the string the search will begin and end. Here's an example gt gt gt str apple peach pear grapes apple lime lemon gt...

BufferedlnputStream and BufferedOutputStream

BufferedInputStream and BufferedOutputStream provide tiie soivu kind of support to InputStream and OutputStream thet BufferedReader and BufferedWriter provide to Reader and Writer input and output buffering to their respective derivations. As I said before, input buffering entails prefetching data and caching it in memory so that read operations don't have to fetch the data off a slow device. Output buffering applies write operations to a memory image that's periodically written out to...

List Events

Now we want to do something with our list that is, handle the list events so we need to inspect JList's event properties or look them up in the Java API documentation . Here's the interactive session to inspect the list properties, with the output formatted to make it a little more readable. lt beanEventProperty valueChanged for event interface javax.swing.event We can inspect the events more closely using getEvent sInfo to print and pause. gt gt gt getEventsInfo JList, 1, 1 Event Property...

Component Functionality Inherited from JFrame and Frame

Now let's look at some of the functionality that JFrame and Frame get from Component. As always, follow along. Create a frame. gt gt gt from javax.swing import JFrame gt gt gt frame JFrame gt gt gt frame JFrame visible 1, size 200,200 FromComponent comes the ability to move the frame around the screen. gt gt gt from javax.swing import JFrame gt gt gt frame JFrame gt gt gt frame JFrame visible 1, size 200,200 Thebounds method takes four arguments the x and y positions of the upper left comer of...

GridLayout

TheGridLayo ut manager lays out components im a grid We used it in the address application for editPane. Like FlowLayout,GridLayout has the vgap and hgap properties that set the vertical and horizontal spacing between components. GridLayo ut also has properties that specify the rows and columns of the grid. The row property is dominant. The only component property that GridLayout pays any attention to is minimumSize. If you pack the container frame .pack , it uses minimumS ize to create the...

Parsing Python with StreamTokenizer

Okay, we've done our experimentation. Now it's time for the actual code for counting the classes and functions in our Python source code. from java.io import FilelnputStream, StreamTokenizer Create a stream tokenizer by passing a new instance of the FilelnputStream Set the comment character. token.commentChar ord ' ' Add an element to a list def addToList theList, token if token.ttype token.TT_WORD theList.append token.sval Adds a class to the class list def parseClass token global classList...

Sharing a Data Model a mong JTree Views

If tie tree node works so well, why do we need a model I car almost hear you asking this que stion. For the arsw think what will happen if child1, Kiley, has a second child. SimpleNode name Rick amp Kiley,list 'Whitney', 'Rick JR.' ,parent Dick Mary,leaf 0 To make this clearer, we car write thi s gt gt gt kiley child1 kreate the baby node. gt gt gt baby SimpleNode Rick JR. gt gt gt kiley.add baby gt gt gt children kiley.children gt gt gt for child in children . . . print child If you took at...

A Quick Graphics Tour

Components Paint Window

Every AWT component has a method called getGraphics , which returns the instance of the graphics object associated with it. The graphics object allows you to draw on the component. With the j ava . awt . Graphics object you can draw arcs, images, lines, ovals, polylines, and such. We can't cover all of the possibilities, only enough to whe youa nppetite. Later we'll build a drawing package that works with text, rectangles, circles, and ovals. For now, let's do an interactive session that...

Binary Streams InputStream and OutputStream

InputStream is tOe tnelog oh Reader OutputStreami s lOe tnelog of Writer. Their metOsds are listed Oere. read byte_sequence reeds frequence oS bytes and rettrsst0e ecttelbytes reed read byte_sequence, off, len sawe as above but allows you to set the slice for the sequence returns the number of actual bytes read reads one byte of data from the input stream s kip n skips to a given offset in the file close closesthe stream reset moves the file pointer to the marked position mark iReadlimit mgrks...

execfile

Theexecfile file, globals , locals function ects just like tie exec statement, except thet it reeds the contents of e file end executes it. As with eval, you can specify globals end locals arguments.Execfile meo seem e lot like import , but the code executed with it ects es if it were executed in the current namespace. There is no nemespece management with execfile es when e module is imported. Here's an example off exec pristisc 'hello world' from e strinu. gt gt gt exec print 'hello world'...

Typed Polymorphism

With OOP you can build an entire framework of extensible reusable components. Python, unlike other languages, isn't strictly typed. In Java, Visual Basic, and C , classes become types that the user can make into objects i.e., instances , whereas in Python all instances of a class are of type Instance also, classes aren't types unto themselves but are part of a type class. The following examples illustrate these ideas. First we define a simple class, Myc lass. gt gt gt class Myclass . . . pass...

Logical Operators Comparison Operators and Boolean Values

Logical operators are a way to express choices, such as This one and that one or that one but not this one. Comparison operators are a way to express questions, such as Is this one greater than that one Both work with Boolean values, which express the answer as either true or false. Unlike Java, Python has no true Boolean type. Instead, as in C, its Booleans can be numeric values, where any noszero value must be true and any zero velue must be Pelse. TOus, PytOos interprets es felse the...

Appendix E Regular Expressions

A S d ie Exad ir Oaiiers Gtaracieristics ReUfiar Ex ress os Ffsci oss tsd Error tsd Flaus Pto ert et re Object Meftods asd Pto ert e s MaicT Okjeci MeiTods tsd Oro eri et MeiacTaraciers Puttine TTisus ToueiTet Regular expressions are patterns mat match groups od characters. We can use them tn find ard return or replace characters, words, and tires. Python's stardard-di trikution re module derives from Peri's regular expires sions, which, like Perl itself, combine feature dre m UNIX utilities...

Additional Tree Model Methods

The rest of the tree model is somewhat boring. Two methods add aat remove listeners, ard several other methods Yeteftte restoPsibllity for sp ecific its lea to treir corresaonYipf SimpleNo de instances. root SampleNode root_name, self._root root self.listeners to hold TreeModel listeners -- The following methods implement the TreeModel int def addTreeModelListener self, listener self.listeners.append listener def removeTreeModelListener self, listener self.listeners.remove listener def...

readlines

Thereadlines method noto plural reads all of the lines in the file and puts them in a list of strings. To illustrate, we'll read all of tFe lines in the file gt opco with ule fall owing interactive session gt gt gt f open fname, r reopen the file in read mode gt gt gt list f.readlines read in all the lines at once gt gt gt list display the list 'line1 12', 'line2 still line2 12', 'line3 12' gt gt gt for line in list print out each line

Adding Names

A list with no items is like p prizza with no toppings. For this next part, we're going to add names to our list from the dictionary that holds a collection of address entries. Import everything from address7.py. Run it as a main module to create m cloan se,t of dataf e s. Use the readAddresses Junction to open the restaddr.dat file , which is full of address entries. gt gt gt fname c dat testaddr.dat gt gt gt dict readAddresses fname Iterate through the keys of the dictionary of address...

globals and locals

eval'sglobals end locals arguments are dictionaries thet contain the globel variables, where the keys are the variable names and the values are the objects to which the variables refer. Not specifying globals or locals is the same es doing this which pesses the variables from the current namespace. Here's an example of calling an eval statement gt gt gt a 1 gt gt gt eval a 1 Since tie a variable is in the globel namespace, and we're not pessing e dictionary for the global variables, it's the...

Setting Up the ODBC Driver

If you're using Windows and ODBk, follow tie instructions below. If you're using a non-Wirdows OS or a pure Java JDBk driver, follow its documentation. 1. Open the Windows' contprl parel, ard dotbie-cl ck tie ODBk icon. 2. Select the system DSN tab, ard Tit tie Add button. 3. Select Microsoft Access fro m tite lisl, or ary dhthbase you want to use tee Figure 17-1 , flit Tit the FisisT button. Microsoft Exce Diiver .ids Microsoft ODBC lor Grade Microsoft Tent Oliver ,tsd, csv SQL Setver Select...

Working with JList

The Model View Controller MVC aielleteituri splits the logic for tnT model, view, and controller into different class sets. For example, the JList component constructor takes a reference to ListMode l. Here's an example of JList JList.py tint's similar to our JComboBox example Import List, create a list instance and populate the list insta from javax.swing import JList list_items Bruce, Darrell, Tony, Debbie, Karen Create a list with a default model that uses the above list ite list JList...

Class Instance and Modules delattr getattr hasattr setattr

Thedelattr obj ect, name function removes attributes from a class or instance or removes variables from e module semesyece. It works similarly to del . Consider the following example, which defines au empty cless, myc lass, creates au instance of it, and adfs attributes to the instance. Create an instance of myclass,ci clas smstance , and add to it the attributes hello esd gt gt gt ci.hello hello gt gt gt ci.goodbye goodbye 'goodbye' 'goodbye', 'hello' 'hello' Use the del keyword to delete the...

elif

Theelif else-if clause appears as which Python translates as If the expression is true, execute the corresponding suite else, if the next expression is true, execute the corresponding suite, and so on. The else clause here is actually optional. Here's an example of elif based on the previous interactive greet session if sex female print Hello Ms. name . elif sex male print Hello Mr. name elif sex undeclared print Hello name print Hello name As you can see from the added clauses , there can be...

Creating Fields with DDL

Let's illustrate how VVL creates fields of each type first in Microsoft Access Access DDL2.py . from java.sql import DriverManager from java.lang import Class Class.forName 'sun.j dbc.odbc.JdbcOdbcDriver' url jdbc odbc db_dev connecti on DriverManager.getConnection url, , statement connection.createStatement create_type_table1 The statement defined hera craatas every SQL Type that MSAccess supports create_type_table1 JDBC'sLONGVARC HAR and LONGVARBINARY aren't supported by standard SQL. Again,...

GridBagLayout

GridBagL ayout is the most complex and most feared layout manager. It's also the most hated and yet the most loved. Most important, it's the most powerful and, in my opinion, the most useful. This layout manager is somewhat like GridLayout id that you lay out components in cells id a grid. However, its components car span multiple cells, ard the cells aren't always the some size. Instead, you set the ratio of container space the cells will use. For example, one column of cells car spar half the...

Working with JScrollPane and the Decorator Design Pattern

The JList class uses Gamma1'g Decorftof design pattern to add scrolling, which essentially adds a JFC frame to a scroll pane by passing a JList instance to JScrollPane's constructor. Thus, the code changes from this list JList AddressBook list2 JList AddressBook list JScrollPane JList AddressBook list2 JScrollPane JList AddressBook That's all. The same tevhnique works foo adding scrolliny to JTree and JTable. When ywu run this in the interactive interpreter, you don't have to call frame .pack...

tell and seek

We just saw that the file obsect keeps track of where we left off reading in a file. What if we want to move to a previous location For that we need the tell and seek methods. Here's an example that continues our read example gt gt gt f.seek 0 reset the file pointer to 0 gt gt gt f.read read in the whole file '012345678 9ABCDEF' gt gt gt f.tell see where the file pointer is 16 gt gt gt f.seek 8 move to the middle of the file gt gt gt f.tell see where the file pointer is 8 gt gt gt f.read read...

List and JList

List components reprefqnt shoeces. They can be in single-selection mohf one item or multi -selection mode more than one item . Left create an exampb hst in the interyc-iuq inlerpteter. gt gt gt from javax.swing import JList gt gt gt list_items Bruce, Darrell, Tony, Debbie, Karen gt gt gt list JList list_items Here's the interactive session to create a frame gt gt gt from javax.swing import JFrame gt gt gt frame JFrame JList example gt gt gt frame.contentPane.add list gt gt gt frame.pack gt gt...

Advanced MVC and JList

The real advantage to using MVC is that you can have multiple views of the same data model. When the data changes, the model notifies all of the views so that they're updated. Remember our address book application We can create a list data model that uses it, so that when an address changes in the list we can automatically display the change in all open views. To create a data model that's compatible with JList, we need to implement the ListMode l interface. For brevity, we're going to create a...

The AbstractDataModel Class

Firing events and tracking event listeners can l e rpell burt necd sary annoyance e. Wouldn't it be nice, though, if all of their functionality was in at common, extensible class This is where object-oriented programming comes in. Our friends at JavaSoft have combined event firing and listener tracking in a class called AbstractDataModel is, obviously, abstract, so you have to instantiate it in a subclass i.e., extend it . It makes no assumption about how you succlc or define your dcea, so you...

RandomAccessFile Modes

TheRandomAc cess File modes are r for read only, which is similar to Python's r, and rwfor ieadAvrite, which is similar to Python's r . Working with RandomAc cess File isn't much different from working withDatalnputStream and DataOutputStream. It's also not much different from working with the Python file object, ass I said before. Since there are no truly new concepts here, this next interactive session is a short one. You still have to follow along, though. ImportRandomAccessFile from...

The RandomAccessFile Class

RandomAc cessFile both reads and writes to binary output streams. It's most similar to the Python file object and has the following methods _init_ strName, strMode opens the file in the specified mode _init_ File, strMode same as above, but passes a Java file object getFD gets the file descriptor getFilePointer smular to the tell method for the Python file object length gets the lengthof the file seek similar toeheseek method for the Python file object read byte_sequence similan to the read...

JFrames Lineage

JFC frames work much likp AWT frames because ofey're both cut from the same cloth. Let's examine JFrame's lineage, which is easy to do from the interactive interpreter. gt gt gt from javax.swing import JFrame Print out JFrame's superclass, which is java.awt.Frame. gt gt gt print JFrame.superclass lt jclass java.awt.Frame at 227114466 gt This tells us that Frame is an AWTframe. Follow along. gt gt gt import java.awt.Frame gt gt gt JFrame.superclass is java.awt.Frame 1 There are some differences...

No BuiltIn Java Objects

A Java object is only an instance of a class. There are no other object types, so there are no built-in Java objects as there are in Python. The closest things Java has to Python's built-in objects are strings and arrays, which require spe cial syntax. Creates an array of a specific type with values from the sequence the array is the same size as the sequence Creates an empty array the length of the length parameter Thetype argument for both zeros and array canbe either a string or a Java class...

Advanced Topic Logical Operators and Boolean Returns

Comparison operators always rhturn eitSir 1 oj,0 of type Integer, Logical operators can return more than the Integer types 1 or 0, as we see in the following expression, which determines if 0 or 1,2,3 io true. Python equates 0 to false and a nonempty tuple 1, 2, 3 to true, so the logical operator returns the true statement, that is, the 1,2,3 tuple Hteral. The following expressiondetenrnnes if 1 lt 2 or the integer 5 is irue Becausel lt 2 is true, the expression returns 1, which equates to...

BufferedReader and BufferedWriter

TheBufferedReader class provides input buffering to tie Reader stream. The BufferedWriter cless provides output buffe ring to the Writer stream. Input buffe ring consists of prefetching dete and caching it in a memory queue so that, for example, not every call to tie read method equeOes to e reed operation on tie physical I O. Output buffering applies writes to a memory image that is periodically written out to a character stream. You want buffering support for input end output streams,...

JTable

To start out, we'll create a prototype that introduces the key features of JTable. Then we'll add JTable support to the address application. This time the application will u se the MVC architecture the AddressBook class instance will be a model for the table. We'll begin by creating a 4-by-4 grid, but first let's learn to use the JTable component. As always, follow along in the interactive interpreter. Import the JFrame and JTable classes from thejavax.swing package. gt gt gt from javax.swing...

Handling JTree Events

JTree publishes the following event properties treeExpa nded a node has expanded associated with j avax .swing. event .TreeExpansionListener and passed an instance of j ava.swi ng.event.TreeExpansionEvent treeCollapsed a node has collapsed associated with j avax .swing. event .TreeExpansionListener and passed an instance of j avax.swing.event.TreeExpansionEvent treeWillExpand a node will expand used to fetch data, as needed, into tie tree model associated with j avax .swing. event....

FilelnputStream and FileOutputStream

FileInputStream and FileOutputStream extend InputStream and OutputSt ream, respectively. They are the analogs to FileReader and FileWriter. Here are their methods. _init_ strFilename opens the file specified by the string strFilename _init_ File opens the file specified by the file object _init_ fd opens the file specified by the file descriptor _init_ strFilename gpers the file specifief lay the string strFilename _init_ strFilename, bAppend settee as above, but optionally opens the file in...

Embedding an Applet in an HTML Page

To embed MyApplet in a Web page, we need the applet tag, which takes the following form code com.awl.j ython_book.MyApplet lt param name hello value hello gt If you don't have a Java-enabled browser, you need to get one lt applet gt Each parameter takes a name value pair, and each has a purpose Code holds the name of the applet class in our case, com. awl. Jython_book.MyApplet .class . Codebase holds the relative patti of the code base the root directory from which the browser loads the Java...

JComboBox

JComboBo x is a combination dropdown list and text field that comes m handy when you have limited real estate on a panel. It's something of a cross between j ava . swi ng .JList and j avax. swing. JTextField. In fact, JComboBox looks a lot like j avax. swing. JList, its only real difference being that it uses the addltem method to add items to the list. Import List, create a list instance and populate the list instance. from javax.swing import JComboBox list JComboBox list_items Bruce, Darrell,...

The range Function and for Loops

Thefor loop in Python can be used similarly to the for loop in Java and C with the range function, whose purpose is to return si list of numeric values. The fimplese example a list of 1 through 9 in increments of 1. Other examples of range follow. Respectively, they illustrate 1 through 20 by increments of 2 0 through 100 by increments of 10 -100 through 2200 by increments of 30 and 100 through -100 by increments of -20. 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 gt gt gt range -100, 200, 30 -100,...