100% found this document useful (2 votes)
10 views

Jython For Java Programmers Bill Robert W pdf download

The document is about 'Jython for Java Programmers' by Robert W. Bill, which serves as a comprehensive guide for Java developers looking to utilize Jython, a combination of Java and Python. It covers various aspects of Jython, including syntax, data types, error handling, and integration with Java, making it a valuable resource for enhancing development flexibility. The book also discusses the history and evolution of Jython, emphasizing its seamless integration with Java and the advantages it offers to programmers.

Uploaded by

lawassyskava
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
10 views

Jython For Java Programmers Bill Robert W pdf download

The document is about 'Jython for Java Programmers' by Robert W. Bill, which serves as a comprehensive guide for Java developers looking to utilize Jython, a combination of Java and Python. It covers various aspects of Jython, including syntax, data types, error handling, and integration with Java, making it a valuable resource for enhancing development flexibility. The book also discusses the history and evolution of Jython, emphasizing its seamless integration with Java and the advantages it offers to programmers.

Uploaded by

lawassyskava
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Jython For Java Programmers Bill Robert W

download

https://ebookbell.com/product/jython-for-java-programmers-bill-
robert-w-21984506

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

The Definitive Guide To Jython Python For The Java Platform


Description Based On Print Version Record Covers Jython 25cover
Includes Index Juneau

https://ebookbell.com/product/the-definitive-guide-to-jython-python-
for-the-java-platform-description-based-on-print-version-record-
covers-jython-25cover-includes-index-juneau-22003002

Python Programming With The Java Class Libraries A Tutorial For


Building Web And Enterprise Applications With Jython 1st Edition
Richard Hightower

https://ebookbell.com/product/python-programming-with-the-java-class-
libraries-a-tutorial-for-building-web-and-enterprise-applications-
with-jython-1st-edition-richard-hightower-62157474

Swing For Jython Robert A Gibson

https://ebookbell.com/product/swing-for-jython-robert-a-gibson-4984372

The Definitive Guide To Jython Python For The Java Platform Wierzbicki

https://ebookbell.com/product/the-definitive-guide-to-jython-python-
for-the-java-platform-wierzbicki-166945820
Scientific Data Analysis Using Jython Scripting And Java Advanced
Information And Knowledge Processing 2010th Edition Chekanov

https://ebookbell.com/product/scientific-data-analysis-using-jython-
scripting-and-java-advanced-information-and-knowledge-
processing-2010th-edition-chekanov-55588674

Websphere Application Server Administration Using Jython 1st Edition


Robert A Gibson

https://ebookbell.com/product/websphere-application-server-
administration-using-jython-1st-edition-robert-a-gibson-2526986
Jython for Java Programmers
By Robert W. Bill

Publisher: New Riders Publishing


Pub Date: December 21, 2001
ISBN: 0-7357-1111-9
Table Pages: 500
of

Content Jython for Java Programmers is an indispensable guide for Java developers
s wishing to accelerate development and increase flexibility using Jython. Jython
itself is the marriage of Java and the increasingly popular high-level programming
language Python. Not only is this book a concise guide to Jython, it is also one
of the most complete guides currently available on integrating Python with the
Java development platform.

Copyright
777
About the Author
About the Technical Reviewers
Acknowledgments
Tell Us What You Think
Introduction
What Is Jython?
Why Jython?
What You Can Expect from This Book
Additional Resources

Part I: Jython
Chapter 1. Jython Syntax, Statements, and Comments
The Interactive Console
Line Separators and Block Indentation Syntax
Comments
Documentation Strings
Statements
Comparing Jython and Java

Chapter 2. Operators, Types, and Built-In Functions


Identifiers
Jython Data Objects
Operators
Built-Ins
Comparison of Jython Data Types and Java Data Types
Java Types

Chapter 3. Errors and Exceptions


Jython Exceptions
Exception Handling
The raise Statement
Tracebacks
The assert Statement and the __debug__ Variable
The Warnings Framework
Comparing Jython and Java
Chapter 4. User-Defined Functions and Variable Scoping
Defining Functions
Namespaces
Recursion
Built-In Functional Programming Tools
Synchronization

Chapter 5. Modules and Packages


The import Statement
A Comparison of Jython and Java
Python's package.module Hierarchy
Java's package.class Hierarchy
Reloading

Chapter 6. Classes, Instances, and Inheritance


Encapsulation, Abstraction, and Information Hiding
Defining Jython Classes
Jython Class and Instance Attributes
Constructors
Finalizer or Destructor
Inheritance
Method Overloading
Sample Classes

Chapter 7. Advanced Classes


Pre-Existing Class Attributes
Pre-Existing Instance Attributes
Special Methods for General Customization
Dynamic Attribute Access
The Callable Hook—__call__
Special Comparison Methods
Object "Truth"
Emulating Built-In Data Objects

Part II: Jython Internals and Integrating Jython With Java


Chapter 8. Compiling Jython with jythonc
What Is jythonc?
Compiling a Module with jythonc
Paths and Compiled Jython
jythonc Options
Java-Compatible Classes

Chapter 9. Embedding and Extending Jython in Java


Embedding Jython
Embedding the InteractiveInterpreter
Embedding an InteractiveConsole
Extending Jython

Part III: Applications with Jython


Chapter 10. GUI Development
Comparing a Java and Jython GUI
Bean Properties and Events
The pawt Package
Examples

Chapter 11. Database Programming


DBM Files
Serialization
Database Management Systems
JDBC
zxJDBC

Chapter 12. Server-Side Web Programming


Jython Servlet Containers
Defining Simple Servlet Classes
More About GenericServlet
HttpServlet
PyServlet
Cookies
Sessions
Databases and Servlets
JSP

Part IV: Appendix


Appendix A. Jython Statements and Built-In Functions Quick Reference

Copyright

Copyright © 2002 by New Riders Publishing

FIRST EDITION: December, 2001

All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic
or mechanical, including photocopying, recording, or by any information storage and retrieval system, without written
permission from the publisher, except for the inclusion of brief quotations in a review.

Library of Congress Catalog Card Number: 00-111656

06 05 04 03 02 7 6 5 4 3 2 1

Interpretation of the printing code: The rightmost double-digit number is the year of the book's printing; the rightmost
single-digit number is the number of the book's printing. For example, the printing code 02-1 shows that the first
printing of the book occurred in 2002.

Composed in Quark and MCPdigital by New Riders Publishing.

Printed in the United States of America.


Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately
capitalized. New Riders Publishing cannot attest to the accuracy of this information. Use of a term in this book should
not be regarded as affecting the validity of any trademark or service mark.

Warning and Disclaimer

This book is designed to provide information about Jython. Every effort has been made to make this book as
complete and as accurate as possible, but no warranty or fitness is implied.

The information is provided on an as-is basis. The authors and New Riders Publishing shall have neither liability nor
responsibility to any person or entity with respect to any loss or damages arising from the information contained in this
book or from the use of the discs or programs that may accompany it.

Credits

Publisher

David Dwyer

Associate Publisher

Stephanie Wall

Production Manager

Gina Kanouse

Managing Editor

Kristy Knoop

Senior Development Editor

Lisa M. Thibault
Project Editor

Todd Zellers

Product Marketing Manager

Stephanie Layton

Publicity Manager

Susan Nixon

Copy Editor

Daryl Kessler

Indexer

Chris Morris

Manufacturing Coordinator

Jim Conway

Book Designer

Louisa Klucznik

Cover Designer

Brainstorm Design, Inc.

Cover Production

Aren Howell

Proofreader
Katherine Shull

Composition

Jeff Bredensteiner

Amy Parker

Dedication

To my wife

About the Author

Robert W. Bill currently dedicates his time to software design and development in Python, Jython, and Java as an
independent contractor. His experiences include a four-year tenure with the Minnesota Educational Computing
Consortium, The Learning Company, and Mattel. Robert has studied at Baylor University, followed by various
courses in music and sciences at the Eastman School of Music and the University of Wisconsin-Madison.

About the Technical Reviewers

These reviewers contributed their considerable hands-on expertise to the entire development process for Jython for
Java Programmers. As the book was being written, these dedicated professionals reviewed all the material for
technical content, organization, and flow. Their feedback was critical to ensuring that Jython for Java Programmers
fits our reader's need for the highest quality technical information.
As member of the research staff at the California Institute of Technology, Dr. Robert Brunner focuses on Knowledge
Discovery and Data-Mining in very large, heavily distributed databases. He also has been a Java and XML instructor
at the Center for Advanced Computing Technology operated by the California State Polytechnic University at
Pomona for the last two years. Recently, he has written a series for Java Developers Journal, reviewed numerous
proposals for a variety of publishing houses, and has edited texts covering Linux, C++, Java, and XML. He is
currently completing Enterprise Java Database Programming to be published by Addison Wesley, Inc.

John Ha is a support engineer and technical writer at NeTraverse, a software development firm in Morrisville, North
Carolina. John is responsible for printed and online documentation for the firm's flagship product, Win4Lin. Win4Lin
allows Microsoft Windows to be installed on a host Linux system. John also investigates distributed filesystem and
remote display technologies for NeTraverse's server product currently under development. John earned his Bachelor
of Arts degree in English Literature from the University of Connecticut in Storrs, Connecticut.

Acknowledgments

Those who work to refine and support Jython prove themselves invaluable day after day. Most notable is Finn Bock,
the Jython project leader. His work currently propels Jython's rapid advance. Other valuable contributors to Jython
and its online community who have helped me in one way or another include Samuele Pedroni, Brian Zimmer, Barry
Warsaw, and many others.

Tell Us What You Think

As the reader of this book, you are the most important critic and commentator. We value your opinion and want to
know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other
words of wisdom you're willing to pass our way.

As the Associate Publisher for New Riders Publishing, I welcome your comments. You can fax, email, or write me
directly to let me know what you did or didn't like about this book—as well as what we can do to make our books
stronger.

Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high
volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book's title and author as well as your name and phone or fax number.
I will carefully review your comments and share them with the author and editors who worked on the book.
Fax: 317-581-4663

Email: nrfeedback@newriders.com

Mail: Stephanie Wall


Associate Publisher
New Riders Publishing
201 West 103rd Street
Indianapolis, IN 46290 USA

Introduction

Jython is the combination of two programming languages—Java and Python—that have achieved tremendous
popularity separately. Java has tremendous acceptance, as evidenced by the number of organizations that deploy
Java-specific applications. Additionally, Java has a huge library of classes to draw from and excellent documentation.
However, Python provides such flexibility, speedy development, and a sense of ease. Choosing between two such
languages would be difficult but, fortunately, is unnecessary thanks to Jython. With Jython, you may implement any
class, algorithm, and pattern in Java or Python without regard for the other language, yet maintain near-seamless
operation between the two languages.

The word seamless is of special significance and recurs throughout this book. Extending other languages, like Perl or
Python, requires the use of a specific API, or annoying wrapper classes. Arbitrary C code will not work in Perl or
Python without additional effort, but arbitrary Java code will work in Jython. Because of the seamless integration with
Java, you can import, use, and even subclass any Java class in Jython. Not just those classes written to follow a
specific API, or those wrapped with special tools, but any Java class. Furthermore, you can compile Jython into Java
byte-code that runs in Java frameworks. You can even import, use, and subclass Python classes from within Java.

Any minor seams that do exist are required to negotiate the differences between Jython and Java, and understanding
such differences helps in understanding Jython. Java is a type-rich language with static typing, whereas Jython uses
dynamic types without explicit type declarations. Java has packages that contain classes, while Jython has packages,
modules, classes, and functions. Java must be compiled, but Jython can run interactively, interpret an uncompiled
script, or be compiled to byte-code. Java classes implement access modifiers such as private and protected; Jython
has only minimal access restrictions and no explicit modifiers like private.

The interesting thing about the differences between Java and Jython is that rather than creating difficulties, these
languages make for ideal complements. Jython's interactive mode is a quick way to test and explore Java classes,
whereas Java's interfaces and abstract classes are a great way to specify protocols for Jython subclasses. Jython's
dynamic typing helps in rapid prototyping and flexibility, while Java's static typing allows for increased runtime
efficiency and type safety. This complement excels because it is seamless. Adding programming overhead to leverage
each of these features would negate their power; fortunately, Jython makes leveraging them intuitive, easy, and free
from detracting overhead.

What Is Jython?

Defining Jython begs the question "What is Python?" Python is a high-level, object-oriented, open-source
programming language implemented in C. Guido Van Rossum was the original developer of Python and continues to
guide a hoard of leading designers and programmers in Python's rapid evolution. The number of developers using
Python has grown rapidly, and continues to do so. However, the advance of Sun's Java programming language is
equally pervasive in the programming landscape. With the number of projects implemented in Java approaching those
in C/C++, there became a need for a Java implementation of Python. Jython, originally called JPython, is just that: the
Java implementation of the Python programming language. To eliminate confusion, this book uses CPython to signify
the C implementation of Python, Jython to signify the Java implementation, and Python to represent the
implementation neutral concepts and design features of the Python language specification.

Jython is a complete programming language—not a Java translator and not just a Python compiler, but a complete
implementation of Python in Java. You can write complete complex applications with Jython itself. Jython also has a
sizable library of modules inherited from CPython. The interesting thing is that Jython, unlike CPython and many other
high-level languages, gives you access to everything it its implementation language, Java. So not only does Jython give
you the Python libraries, it also gives you all available Java classes. This makes for a truly large library of resources.

Jython, and Python, emphasizes code clarity, simplicity, and legibility. Jython uses indentation to delimit code blocks
to avoid the braces found in Java. Jython uses a newline to denote the beginning of a new statement, with a few
important exceptions, allowing for the elimination of a semicolon at the end of each statement. Jython foregoes
attribute access modifiers such as Java's public, private, and protected, giving the programmer the flexibility required
for rapid development and to focus on program logic. And as mentioned earlier, Jython does not use explicit static
typing, so there are no type declarations to distract from program logic.

Jython's history begins with Jim Hugunin, a colleague of Guido Van Rossum at the Center for National Research
Incentives (CNRI), who recognized the need for a Java implementation of the Python programming language and
implemented it under the original name JPython. Eventually, Jim Hugunin was unable to continue working on JPython
because of an opportunity to develop aspectj (http://aspectj.org/). Therefore, Barry Warsaw, also at CNRI at that
time, continued as the project leader during a time when Python developers were preparing to move away from
CNRI.

The move away from CNRI was a transition toward the more open development model at Sourceforge where the
Python and Jython projects currently reside. During this time, Finn Bock, a major contributor to Jython (JPython),
took the reins of the Jython project. It is in a very large part due to Finn Bock's extremely prolific and quality
additions to Jython that it has become such a valuable tool. Open-source projects like Jython excel only as much as
those that develop and maintain them, and Jython has proven to be most fortunate in this regard because of Finn
Bock's contributions and guidance. Another more recent and valuable contributor to Jython is Samuele Pedroni.
Recent advancements in Jython's classloading, import mechanisms, and more is thanks to Samuele's contributions.
Finn and Samuele are currently the two primary developers of Jython.

Why Jython?

Jython is unique in that it inherits the desirable traits of both Java and Python. The sections that follow describe each
of the traits and their benefits.

Seamless Access to Java Classes

Implementing Python in Java makes for an interesting look at the usefulness of Java's Reflection API. Reflection
allows Jython to seamlessly use most any Java class. Jython inherits a number of advantages from CPython, but
CPython has a bump between C and Python that restricts the usefulness of C libraries other than those specifically
written for Python. Eliminating this bump in Jython truly has an impact of productivity and effectiveness.

Because of the seamless fit with Java, Jython can benefit any organization that deploys Java applications and
frameworks without any additional work. Adopting another development language is a monumental and weighty
decision for most organizations because of the implications for frameworks, servers, and peripheral tools. Jython,
however, seamlessly masquerades as Java, making it but a seamless addition to an existing Java repertoire rather than
a weighty decision. This is not the case for other high-level languages. A vast number of organizations have towering
investments in Java that reduce the benefit, or at least the appeal, of CPython, Perl, Ruby, PHP, and other high-level
languages that do not transparently leverage existing Java implementations. Jython, on the other hand, is a powerful
complement to existing Java frameworks that blends in transparently.

Efficiency

A fair calculation of efficiency is a broad topic that must account for programmer time, total complexity, lines of code,
reusability, maintainability, and runtime efficiency. Of course, many people disagree on the weight assigned to these
variables, and more often than not the situation at hand dictates which is favored in the calculation; however, it is the
premise of this book that Jython exceeds other languages in all areas but runtime efficiency. Jython's runtime speed
compares well with other high-level languages, but speed is never the goal or advantage of a high-level language. The
difference, however, is that when accelerating an application is required it is easier to translate Jython code into Java
because of Jython's seamless integration with Java. Additionally, the direct access to all available Java classes
increases the likelihood of leveraging existing classes.

Dynamic Types

You do not declare types in Jython as you would in Java because types are determined at runtime. Jython's list and
mapping types are high-level, polymorphic objects that are instances of Java classes. Polymorphic means that an
object works for differing types of data. Jython's list type, for example, can be a sequence of numbers, strings,
characters, or a combination of types. Dynamic and polymorphic types are a dramatic contribution to programmer
efficiency, reduced lines of code, and reduced complexity, as evidenced in numerous high-level languages that forgo
explicit, static, and primitive types.

Introspection and Dynamic Execution

Jython has built-in functions that allow easy object introspections and dynamic execution of code. Introspection is the
ability to discover information about an object, while dynamic execution is the ability to execute code that is
generated at runtime.This functionality dramatically reduces lines of code and programmer efficiency while easing
maintainability.This also allows a close integration of data and program structure or logic without affecting reusability
because everything is determined at runtime.

First-Class Functions and Functional Programming

Jython, as does Python, has first-class functions. A first-class function is a callable object that can be passed around
like any variable. First-class functions are valuable to event handling and many other situations, leading to Java's
addition of inner classes. Although Java's inner classes are similar to first-class functions, they do not compare with
the ease and flexibility of using Jython's first-class functions because of the reduced syntax overhead in Jython.

Jython also includes all the tools required for functional programming.This means that imperative, object-oriented,
and functional programming approaches are supported in Jython.This is obviously an educational advantage, but it
also allows a Jython programmer to choose the paradigm most appropriate to the situation rather than that imposed
by the language. Functional tools such as list comprehension, lambda forms, map, filter, and reduce, also can have a
dramatic affect on reducing lines of code, complexity, and the number of name rebindings (name rebindings increase
risk of negative side effects, such as bugs).

Short Learning Curve

Any Java programmer can become proficient in Jython within days. As with many things, the art is in the details, but
the ability to leverage the rapid development capabilities of Jython within only a few days is valuable.The ability to
easily acquire Jython facility in testing and support groups that would not normally have time to study complex Java
code can raise an organization's technical level and efficiency without incurring high training overhead.

Write Once, Run Anywhere

Because Jython is written in Java, and because it compiles into Java byte-code, Jython also benefits from Java's
"write once, run anywhere" approach. Jython runs on any platform with a compliant Java 1.1 or greater Java Virtual
Manager ( JVM). Additionally, you can fully compile Jython applications into byte-code that is fully self-sufficient,
and can run on any complaint JVM. Applications compiled on Linux will run on any other platform with a compliant
JVM.

Java Security

Java's security is exceptional, and increasingly important. From sandbox to signatures, Jython has the potential to use
Java's truly exceptional security framework.

Code Clarity

Code clarity is the Holy Grail of Python, and of course Jython. Unnecessary punctuation and line noise is avoided.
Jython code should approach natural language in legibility and clarity.This begins with Python's commitment to
whitespace delineation of code blocks and statements. Indentation marks code blocks and new lines mark new
statements. Beyond that, the syntax is always chosen to favor clarity. Maintaining Jython code is easier because it is
more clear.

Unicode and Internationalization

Jython uses Java's unicode implementation, allowing for easy implementation of international products.

Hotspot and Development Efficiency

Jython's speed is reasonable, but not as fast as pure Java.The major advantages to Jython are in development and
maintenance time; however, multi-level language development has strong precedence, most notable in Java's Hotspot
technology. Hotspot optimizes those sections of a program that are in most need of optimization. The theory is that
only a small portion of a program incurs a large portion of its execution time. Only optimizing those portions of code
that have a large effect on performance makes the most sense. Doing the same when developing the code is equally
sensible. Using Jython to write an application and then converting processor-intensive classes to Java is the ideal
combination of runtime performance and programmer efficiency. The Hotspot analogy makes multi-level language
development with Jython and Java a convincing development model.

What You Can Expect from This Book

This book is designed for those who know Java or are learning Java. The Java-specific meaning of terms such as
classpath, garbage collection, and interface appear without explanation, but no more than rudimentary Java
knowledge is required. Specifically, Java developers desiring accelerated development, embedded interpreters, and
increased flexibility will most appreciate this book. Although Jython is a complete programming language, it is unique
in its ability to complement Java development rather than appear as an alternative to Java.

Chapter 1, "Jython Syntax, Statements, and Comments," introduces syntax and statements. Python's syntax is an
essential part of what constitutes the coined word pythonic, an important descriptor of those details that make Python
and Jython code clear, simple, and distinct. Python's use of indentation to delimit code blocks and newlines to delimit
statements is new to most programmers, and Chapter 1 details the rules that apply to indentation, newlines, and
statements. Additionally, Chapter 1 introduces the interactive interpreter, a Jython mode that immediately evaluates
statements as you enter them.This chapter applies to Python in general with no references to material unique to Jython.

Chapter 2, "Operators, Types, and Built-In Functions," covers Jython's data object, operators, and built-in functions.
Data objects, or types, are especially interesting because of Jython's ability to use both Python and Java objects. The
Python language specification defines Python's, and therefore Jython's types, but types are where Jython-specific
details emerge. One such detail is the conversion between Jython and Java types. Chapter 2 also defines Jython's
built-in functions, which are those functions that are available without any import statements and that account for a
sizable portion of Jython's functionality.

Jython's errors, exceptions, and warnings appear in Chapter 3, "Errors and Exceptions." Chapter 3 contains the
definitions of Jython's built-in exceptions as well as a detailed look at the try/except and try/finally statements used to
handle exceptions. Working with exceptions is of course important to Jython, but it is also an important step to
working with Java classes and the exceptions they may raise.

Java does not have functions, but they are an important part of Jython. Chapter 4, "User-Defined Functions and
Variable Scoping," shows how to define and use Jython functions and how to use Jython's functional programming
tools. Functions are callable objects not defined within a class, but functional programming has a less succinct
definition. Functional programming revolves around finding the results of an expression. Jython supplies all the tools
required to learn and use functional programming, and these tools appear in Chapter 2.

Jython has modules, another unit that Java does not have, and Chapter 5, "Modules and Packages," describes
Jython's modules. Jython also has packages, as does Java, but Jython packages differ from the Java counterpart as
Chapter 5 explains. With Jython packages, modules, and classes as well as Java packages and classes, the details of
the import statement quickly become important. Chapter 5 clarifies the import statement along with modules and
packages.

Chapter 6, "Classes, Instances, and Inheritance," introduces the definition and use of Jython classes. This includes the
subclassing of Java classes, the use of Java interfaces and Java abstract classes, and the implications of Java's access
modifiers such as public, private, and protected. Jython classes do differ from Java classes, however, and Chapter 6
clarifies these differences.
Chapter 7, "Advanced Classes," extends the information on Jython classes to include Jython's special class attributes.
Special attributes in Jython are those that follow a special naming convention and provide specific functionality. These
special attributes let you customize a class's behavior and makes creating advanced classes relatively easy.

Chapter 8, "Compiling Jython with jythonc jythonc," details Jython's complicated jythonc tool. jythonc compiles
Jython code to Java byte-code. jythonc lets you use classes written in Jython within Java frameworks, and even lets
you create class files that you can import and use from within Java.

Chapter 9, "Embedding and Extending Jython in Java," describes how to embed a Jython interpreter. Compiling
Jython to Java byte-code is extremely useful, but embedding a Jython interpreter within Java applications has many
advantages. Embedding gives you total control over Jython's system state and allows you to use all of Jython's
features and modules within a Java application. The amazing part is how simple it is to embed a Jython interpreter. A
basic embedded interpreter requires only two lines of Java code, and adding additional configuration to an embedded
interpreter is equally easy. An embedded interpreter allows you to write Jython modules to extend or implement
features of Java applications without having to compile modules with jythonc. It is my impression that embedding
Jython is the foremost advantage of Jython. It allows multi-level language development, leverages all that is good in
Java and Python within a single application, and allows rapid development and extensibility. There is already a
number of projects that embed Jython, and the trend to do so will likely continue.

Chapter 10, "GUI Development," describes how to develop graphical applications with Jython. The focus is on
Java's Abstract Windowing Toolkit (AWT) and Swing application programmer's interface. Jython allows rapid
development of graphical applications because of its addition of automatic bean properties and events. Chapter 10
covers the details of automatic bean properties and events, but the basic idea is that Jython automatically searches a
component for these features and adds shortcuts to establishing properties and event handlers. The shortcuts leverage
Jython syntax features to simplify and accelerate development. Chapter 10 also includes information on creating Java
applets with Jython.

Java has become very prominent in database programming, and Jython is able to leverage all of Java's success in this
area while adding its own advantages. Chapter 11, "Database Programming," introduces the use of Jython in
database programming. Chapter 11 includes information on hashed database files as well as the MySQL and
PostgreSQL relation database management systems (object-relation for PostgreSQL). Jython also has the advantage
of being able to use Java's JDBC database connectivity or the Python database application programmer's interface
implemented with zxJDBC. Chapter 11 discusses both of these APIs.

Chapter 12, "Server-Side Web Programming," describes web programming with Jython. For Jython, this means
servlets, Java Server Pages (JSP), and taglibs. In other words, server-side web development with Jython coincides
with the popular (standard) Java web development paradigm. Chapter 12 addresses using jythonc -compiled classes
as servlets as well as an embedded Jython Servlet mapping and IBM's bean scripting framework (BSF).

Who This Book Is For

This book best fits those programmers already familiar with Java but who are interested Jython. This creates a wide
range of potential readers, and further clarification follows to help narrow the field. Java programmers wishing to add
a high-level language as a tool in their existing arsenal is the primary audience, but is equally applicable to those
seeking an alternative to Java, yet bound to an organization dedicated to Java-based technology. A secondary
audience is those beginning Python programmers wishing to extent their Python facility within Java frameworks.
Because this book assumes some knowledge of Java basics, this secondary audience may require an additional
source for Java fundamentals.
A distant tertiary audience would be those new to programming, but this requires careful qualification. This book
alone is insufficient as an introduction to programming. At a minimum, an additional resource on the fundamentals of
Java is required. The reason that this is a reasonable view is that Jython (and Python) is an ideal learning language.
The Python language embodies clarity and simplicity while its interactive interpreter allows experimentation,
immediate feedback, and rapid acquisition of language features. The fact that Jython supports functional programming
as well as object-oriented programming is an educational advantage.

Who This Book Isn't For

If you have no interest in Java, then this book is not for you. Jython requires an understanding of Java, and those who
do not know Java, or do not intent to pursue it in parallel with this book, will not benefit from this book. The
advantage of Jython is its ability to masquerade as Java and to seamlessly use Java libraries. This means the absence
of a basic conviction to Java-centric tools makes Jython, and this book, a poor choice for your needs.

If you are already an advanced Python programmer, this book may not be for you. A substantial portion of this book
is Python syntax and usage. Java-specific examples and information do appear, but only within larger sections on
syntax and usage that an experienced Python program may find too repetitious.

Additional Resources

Jython-related Internet resources, and the reason for their significance, are listed in this section.

http://www.jython.org/ Jython's official home page.


http://www.python.org/ Python's official home page. Python has a great collection of documentation available
at this site that is also applicable to Jython.

http://www.digisprings.com/jython/ The website associated with this book.You will find additional Jython
information, as well as book errata, tips, and more at this site.

http://sourceforge.net/projects/zxjdbc This is the project page for the zxJDBC package. This package
provides Python 2.0 database functionality for Jython.

Mailing lists specific to Jython are a valuable resource. It is best to subscribe to such lists from the links available on
Jython's home page, and the lists available are jython-users, jython-dev, and jython-announce. The jython-users list is
designed for general Jython questions and help, whereas the jython-dev list is for matters related to the development
of Jython itself (as opposed to development with Jython). The announce list is a low-volume list designed to keep
users posted about new releases. If you face problems that are not addressed in the book, at
http://www.newriders.com/, or at the Jython website, it is best to consult the mailing lists.
Jython for Java Programmers
By Robert W. Bill

Publisher: New Riders Publishing


Pub Date: December 21, 2001
ISBN: 0-7357-1111-9
Table Pages: 500
of

Content Jython for Java Programmers is an indispensable guide for Java developers
s wishing to accelerate development and increase flexibility using Jython. Jython
itself is the marriage of Java and the increasingly popular high-level programming
language Python. Not only is this book a concise guide to Jython, it is also one
of the most complete guides currently available on integrating Python with the
Java development platform.

Copyright
777
About the Author
About the Technical Reviewers
Acknowledgments
Tell Us What You Think
Introduction
What Is Jython?
Why Jython?
What You Can Expect from This Book
Additional Resources

Part I: Jython
Chapter 1. Jython Syntax, Statements, and Comments
The Interactive Console
Line Separators and Block Indentation Syntax
Comments
Documentation Strings
Statements
Comparing Jython and Java

Chapter 2. Operators, Types, and Built-In Functions


Identifiers
Jython Data Objects
Operators
Built-Ins
Comparison of Jython Data Types and Java Data Types
Java Types

Chapter 3. Errors and Exceptions


Jython Exceptions
Exception Handling
The raise Statement
Tracebacks
The assert Statement and the __debug__ Variable
The Warnings Framework
Comparing Jython and Java
Chapter 4. User-Defined Functions and Variable Scoping
Defining Functions
Namespaces
Recursion
Built-In Functional Programming Tools
Synchronization

Chapter 5. Modules and Packages


The import Statement
A Comparison of Jython and Java
Python's package.module Hierarchy
Java's package.class Hierarchy
Reloading

Chapter 6. Classes, Instances, and Inheritance


Encapsulation, Abstraction, and Information Hiding
Defining Jython Classes
Jython Class and Instance Attributes
Constructors
Finalizer or Destructor
Inheritance
Method Overloading
Sample Classes

Chapter 7. Advanced Classes


Pre-Existing Class Attributes
Pre-Existing Instance Attributes
Special Methods for General Customization
Dynamic Attribute Access
The Callable Hook—__call__
Special Comparison Methods
Object "Truth"
Emulating Built-In Data Objects

Part II: Jython Internals and Integrating Jython With Java


Chapter 8. Compiling Jython with jythonc
What Is jythonc?
Compiling a Module with jythonc
Paths and Compiled Jython
jythonc Options
Java-Compatible Classes

Chapter 9. Embedding and Extending Jython in Java


Embedding Jython
Embedding the InteractiveInterpreter
Embedding an InteractiveConsole
Extending Jython

Part III: Applications with Jython


Chapter 10. GUI Development
Comparing a Java and Jython GUI
Bean Properties and Events
The pawt Package
Examples

Chapter 11. Database Programming


DBM Files
Serialization
Database Management Systems
JDBC
zxJDBC

Chapter 12. Server-Side Web Programming


Jython Servlet Containers
Defining Simple Servlet Classes
More About GenericServlet
HttpServlet
PyServlet
Cookies
Sessions
Databases and Servlets
JSP

Part IV: Appendix


Appendix A. Jython Statements and Built-In Functions Quick Reference

Copyright

Copyright © 2002 by New Riders Publishing

FIRST EDITION: December, 2001

All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic
or mechanical, including photocopying, recording, or by any information storage and retrieval system, without written
permission from the publisher, except for the inclusion of brief quotations in a review.

Library of Congress Catalog Card Number: 00-111656

06 05 04 03 02 7 6 5 4 3 2 1

Interpretation of the printing code: The rightmost double-digit number is the year of the book's printing; the rightmost
single-digit number is the number of the book's printing. For example, the printing code 02-1 shows that the first
printing of the book occurred in 2002.

Composed in Quark and MCPdigital by New Riders Publishing.

Printed in the United States of America.


Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately
capitalized. New Riders Publishing cannot attest to the accuracy of this information. Use of a term in this book should
not be regarded as affecting the validity of any trademark or service mark.

Warning and Disclaimer

This book is designed to provide information about Jython. Every effort has been made to make this book as
complete and as accurate as possible, but no warranty or fitness is implied.

The information is provided on an as-is basis. The authors and New Riders Publishing shall have neither liability nor
responsibility to any person or entity with respect to any loss or damages arising from the information contained in this
book or from the use of the discs or programs that may accompany it.

Credits

Publisher

David Dwyer

Associate Publisher

Stephanie Wall

Production Manager

Gina Kanouse

Managing Editor

Kristy Knoop

Senior Development Editor

Lisa M. Thibault
Project Editor

Todd Zellers

Product Marketing Manager

Stephanie Layton

Publicity Manager

Susan Nixon

Copy Editor

Daryl Kessler

Indexer

Chris Morris

Manufacturing Coordinator

Jim Conway

Book Designer

Louisa Klucznik

Cover Designer

Brainstorm Design, Inc.

Cover Production

Aren Howell

Proofreader
Katherine Shull

Composition

Jeff Bredensteiner

Amy Parker

Dedication

To my wife

About the Author

Robert W. Bill currently dedicates his time to software design and development in Python, Jython, and Java as an
independent contractor. His experiences include a four-year tenure with the Minnesota Educational Computing
Consortium, The Learning Company, and Mattel. Robert has studied at Baylor University, followed by various
courses in music and sciences at the Eastman School of Music and the University of Wisconsin-Madison.

About the Technical Reviewers

These reviewers contributed their considerable hands-on expertise to the entire development process for Jython for
Java Programmers. As the book was being written, these dedicated professionals reviewed all the material for
technical content, organization, and flow. Their feedback was critical to ensuring that Jython for Java Programmers
fits our reader's need for the highest quality technical information.
As member of the research staff at the California Institute of Technology, Dr. Robert Brunner focuses on Knowledge
Discovery and Data-Mining in very large, heavily distributed databases. He also has been a Java and XML instructor
at the Center for Advanced Computing Technology operated by the California State Polytechnic University at
Pomona for the last two years. Recently, he has written a series for Java Developers Journal, reviewed numerous
proposals for a variety of publishing houses, and has edited texts covering Linux, C++, Java, and XML. He is
currently completing Enterprise Java Database Programming to be published by Addison Wesley, Inc.

John Ha is a support engineer and technical writer at NeTraverse, a software development firm in Morrisville, North
Carolina. John is responsible for printed and online documentation for the firm's flagship product, Win4Lin. Win4Lin
allows Microsoft Windows to be installed on a host Linux system. John also investigates distributed filesystem and
remote display technologies for NeTraverse's server product currently under development. John earned his Bachelor
of Arts degree in English Literature from the University of Connecticut in Storrs, Connecticut.

Acknowledgments

Those who work to refine and support Jython prove themselves invaluable day after day. Most notable is Finn Bock,
the Jython project leader. His work currently propels Jython's rapid advance. Other valuable contributors to Jython
and its online community who have helped me in one way or another include Samuele Pedroni, Brian Zimmer, Barry
Warsaw, and many others.

Tell Us What You Think

As the reader of this book, you are the most important critic and commentator. We value your opinion and want to
know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other
words of wisdom you're willing to pass our way.

As the Associate Publisher for New Riders Publishing, I welcome your comments. You can fax, email, or write me
directly to let me know what you did or didn't like about this book—as well as what we can do to make our books
stronger.

Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high
volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book's title and author as well as your name and phone or fax number.
I will carefully review your comments and share them with the author and editors who worked on the book.
Fax: 317-581-4663

Email: nrfeedback@newriders.com

Mail: Stephanie Wall


Associate Publisher
New Riders Publishing
201 West 103rd Street
Indianapolis, IN 46290 USA

Introduction

Jython is the combination of two programming languages—Java and Python—that have achieved tremendous
popularity separately. Java has tremendous acceptance, as evidenced by the number of organizations that deploy
Java-specific applications. Additionally, Java has a huge library of classes to draw from and excellent documentation.
However, Python provides such flexibility, speedy development, and a sense of ease. Choosing between two such
languages would be difficult but, fortunately, is unnecessary thanks to Jython. With Jython, you may implement any
class, algorithm, and pattern in Java or Python without regard for the other language, yet maintain near-seamless
operation between the two languages.

The word seamless is of special significance and recurs throughout this book. Extending other languages, like Perl or
Python, requires the use of a specific API, or annoying wrapper classes. Arbitrary C code will not work in Perl or
Python without additional effort, but arbitrary Java code will work in Jython. Because of the seamless integration with
Java, you can import, use, and even subclass any Java class in Jython. Not just those classes written to follow a
specific API, or those wrapped with special tools, but any Java class. Furthermore, you can compile Jython into Java
byte-code that runs in Java frameworks. You can even import, use, and subclass Python classes from within Java.

Any minor seams that do exist are required to negotiate the differences between Jython and Java, and understanding
such differences helps in understanding Jython. Java is a type-rich language with static typing, whereas Jython uses
dynamic types without explicit type declarations. Java has packages that contain classes, while Jython has packages,
modules, classes, and functions. Java must be compiled, but Jython can run interactively, interpret an uncompiled
script, or be compiled to byte-code. Java classes implement access modifiers such as private and protected; Jython
has only minimal access restrictions and no explicit modifiers like private.

The interesting thing about the differences between Java and Jython is that rather than creating difficulties, these
languages make for ideal complements. Jython's interactive mode is a quick way to test and explore Java classes,
whereas Java's interfaces and abstract classes are a great way to specify protocols for Jython subclasses. Jython's
dynamic typing helps in rapid prototyping and flexibility, while Java's static typing allows for increased runtime
efficiency and type safety. This complement excels because it is seamless. Adding programming overhead to leverage
each of these features would negate their power; fortunately, Jython makes leveraging them intuitive, easy, and free
from detracting overhead.

What Is Jython?

Defining Jython begs the question "What is Python?" Python is a high-level, object-oriented, open-source
programming language implemented in C. Guido Van Rossum was the original developer of Python and continues to
guide a hoard of leading designers and programmers in Python's rapid evolution. The number of developers using
Python has grown rapidly, and continues to do so. However, the advance of Sun's Java programming language is
equally pervasive in the programming landscape. With the number of projects implemented in Java approaching those
in C/C++, there became a need for a Java implementation of Python. Jython, originally called JPython, is just that: the
Java implementation of the Python programming language. To eliminate confusion, this book uses CPython to signify
the C implementation of Python, Jython to signify the Java implementation, and Python to represent the
implementation neutral concepts and design features of the Python language specification.

Jython is a complete programming language—not a Java translator and not just a Python compiler, but a complete
implementation of Python in Java. You can write complete complex applications with Jython itself. Jython also has a
sizable library of modules inherited from CPython. The interesting thing is that Jython, unlike CPython and many other
high-level languages, gives you access to everything it its implementation language, Java. So not only does Jython give
you the Python libraries, it also gives you all available Java classes. This makes for a truly large library of resources.

Jython, and Python, emphasizes code clarity, simplicity, and legibility. Jython uses indentation to delimit code blocks
to avoid the braces found in Java. Jython uses a newline to denote the beginning of a new statement, with a few
important exceptions, allowing for the elimination of a semicolon at the end of each statement. Jython foregoes
attribute access modifiers such as Java's public, private, and protected, giving the programmer the flexibility required
for rapid development and to focus on program logic. And as mentioned earlier, Jython does not use explicit static
typing, so there are no type declarations to distract from program logic.

Jython's history begins with Jim Hugunin, a colleague of Guido Van Rossum at the Center for National Research
Incentives (CNRI), who recognized the need for a Java implementation of the Python programming language and
implemented it under the original name JPython. Eventually, Jim Hugunin was unable to continue working on JPython
because of an opportunity to develop aspectj (http://aspectj.org/). Therefore, Barry Warsaw, also at CNRI at that
time, continued as the project leader during a time when Python developers were preparing to move away from
CNRI.

The move away from CNRI was a transition toward the more open development model at Sourceforge where the
Python and Jython projects currently reside. During this time, Finn Bock, a major contributor to Jython (JPython),
took the reins of the Jython project. It is in a very large part due to Finn Bock's extremely prolific and quality
additions to Jython that it has become such a valuable tool. Open-source projects like Jython excel only as much as
those that develop and maintain them, and Jython has proven to be most fortunate in this regard because of Finn
Bock's contributions and guidance. Another more recent and valuable contributor to Jython is Samuele Pedroni.
Recent advancements in Jython's classloading, import mechanisms, and more is thanks to Samuele's contributions.
Finn and Samuele are currently the two primary developers of Jython.

Why Jython?

Jython is unique in that it inherits the desirable traits of both Java and Python. The sections that follow describe each
of the traits and their benefits.

Seamless Access to Java Classes

Implementing Python in Java makes for an interesting look at the usefulness of Java's Reflection API. Reflection
allows Jython to seamlessly use most any Java class. Jython inherits a number of advantages from CPython, but
CPython has a bump between C and Python that restricts the usefulness of C libraries other than those specifically
written for Python. Eliminating this bump in Jython truly has an impact of productivity and effectiveness.

Because of the seamless fit with Java, Jython can benefit any organization that deploys Java applications and
frameworks without any additional work. Adopting another development language is a monumental and weighty
decision for most organizations because of the implications for frameworks, servers, and peripheral tools. Jython,
however, seamlessly masquerades as Java, making it but a seamless addition to an existing Java repertoire rather than
a weighty decision. This is not the case for other high-level languages. A vast number of organizations have towering
investments in Java that reduce the benefit, or at least the appeal, of CPython, Perl, Ruby, PHP, and other high-level
languages that do not transparently leverage existing Java implementations. Jython, on the other hand, is a powerful
complement to existing Java frameworks that blends in transparently.

Efficiency

A fair calculation of efficiency is a broad topic that must account for programmer time, total complexity, lines of code,
reusability, maintainability, and runtime efficiency. Of course, many people disagree on the weight assigned to these
variables, and more often than not the situation at hand dictates which is favored in the calculation; however, it is the
premise of this book that Jython exceeds other languages in all areas but runtime efficiency. Jython's runtime speed
compares well with other high-level languages, but speed is never the goal or advantage of a high-level language. The
difference, however, is that when accelerating an application is required it is easier to translate Jython code into Java
because of Jython's seamless integration with Java. Additionally, the direct access to all available Java classes
increases the likelihood of leveraging existing classes.

Dynamic Types

You do not declare types in Jython as you would in Java because types are determined at runtime. Jython's list and
mapping types are high-level, polymorphic objects that are instances of Java classes. Polymorphic means that an
object works for differing types of data. Jython's list type, for example, can be a sequence of numbers, strings,
characters, or a combination of types. Dynamic and polymorphic types are a dramatic contribution to programmer
efficiency, reduced lines of code, and reduced complexity, as evidenced in numerous high-level languages that forgo
explicit, static, and primitive types.

Introspection and Dynamic Execution

Jython has built-in functions that allow easy object introspections and dynamic execution of code. Introspection is the
ability to discover information about an object, while dynamic execution is the ability to execute code that is
generated at runtime.This functionality dramatically reduces lines of code and programmer efficiency while easing
maintainability.This also allows a close integration of data and program structure or logic without affecting reusability
because everything is determined at runtime.

First-Class Functions and Functional Programming

Jython, as does Python, has first-class functions. A first-class function is a callable object that can be passed around
like any variable. First-class functions are valuable to event handling and many other situations, leading to Java's
addition of inner classes. Although Java's inner classes are similar to first-class functions, they do not compare with
the ease and flexibility of using Jython's first-class functions because of the reduced syntax overhead in Jython.

Jython also includes all the tools required for functional programming.This means that imperative, object-oriented,
and functional programming approaches are supported in Jython.This is obviously an educational advantage, but it
also allows a Jython programmer to choose the paradigm most appropriate to the situation rather than that imposed
by the language. Functional tools such as list comprehension, lambda forms, map, filter, and reduce, also can have a
dramatic affect on reducing lines of code, complexity, and the number of name rebindings (name rebindings increase
risk of negative side effects, such as bugs).

Short Learning Curve

Any Java programmer can become proficient in Jython within days. As with many things, the art is in the details, but
the ability to leverage the rapid development capabilities of Jython within only a few days is valuable.The ability to
easily acquire Jython facility in testing and support groups that would not normally have time to study complex Java
code can raise an organization's technical level and efficiency without incurring high training overhead.

Write Once, Run Anywhere

Because Jython is written in Java, and because it compiles into Java byte-code, Jython also benefits from Java's
"write once, run anywhere" approach. Jython runs on any platform with a compliant Java 1.1 or greater Java Virtual
Manager ( JVM). Additionally, you can fully compile Jython applications into byte-code that is fully self-sufficient,
and can run on any complaint JVM. Applications compiled on Linux will run on any other platform with a compliant
JVM.

Java Security

Java's security is exceptional, and increasingly important. From sandbox to signatures, Jython has the potential to use
Java's truly exceptional security framework.

Code Clarity

Code clarity is the Holy Grail of Python, and of course Jython. Unnecessary punctuation and line noise is avoided.
Jython code should approach natural language in legibility and clarity.This begins with Python's commitment to
whitespace delineation of code blocks and statements. Indentation marks code blocks and new lines mark new
statements. Beyond that, the syntax is always chosen to favor clarity. Maintaining Jython code is easier because it is
more clear.

Unicode and Internationalization

Jython uses Java's unicode implementation, allowing for easy implementation of international products.

Hotspot and Development Efficiency

Jython's speed is reasonable, but not as fast as pure Java.The major advantages to Jython are in development and
maintenance time; however, multi-level language development has strong precedence, most notable in Java's Hotspot
technology. Hotspot optimizes those sections of a program that are in most need of optimization. The theory is that
only a small portion of a program incurs a large portion of its execution time. Only optimizing those portions of code
that have a large effect on performance makes the most sense. Doing the same when developing the code is equally
sensible. Using Jython to write an application and then converting processor-intensive classes to Java is the ideal
combination of runtime performance and programmer efficiency. The Hotspot analogy makes multi-level language
development with Jython and Java a convincing development model.

What You Can Expect from This Book

This book is designed for those who know Java or are learning Java. The Java-specific meaning of terms such as
classpath, garbage collection, and interface appear without explanation, but no more than rudimentary Java
knowledge is required. Specifically, Java developers desiring accelerated development, embedded interpreters, and
increased flexibility will most appreciate this book. Although Jython is a complete programming language, it is unique
in its ability to complement Java development rather than appear as an alternative to Java.

Chapter 1, "Jython Syntax, Statements, and Comments," introduces syntax and statements. Python's syntax is an
essential part of what constitutes the coined word pythonic, an important descriptor of those details that make Python
and Jython code clear, simple, and distinct. Python's use of indentation to delimit code blocks and newlines to delimit
statements is new to most programmers, and Chapter 1 details the rules that apply to indentation, newlines, and
statements. Additionally, Chapter 1 introduces the interactive interpreter, a Jython mode that immediately evaluates
statements as you enter them.This chapter applies to Python in general with no references to material unique to Jython.

Chapter 2, "Operators, Types, and Built-In Functions," covers Jython's data object, operators, and built-in functions.
Data objects, or types, are especially interesting because of Jython's ability to use both Python and Java objects. The
Python language specification defines Python's, and therefore Jython's types, but types are where Jython-specific
details emerge. One such detail is the conversion between Jython and Java types. Chapter 2 also defines Jython's
built-in functions, which are those functions that are available without any import statements and that account for a
sizable portion of Jython's functionality.

Jython's errors, exceptions, and warnings appear in Chapter 3, "Errors and Exceptions." Chapter 3 contains the
definitions of Jython's built-in exceptions as well as a detailed look at the try/except and try/finally statements used to
handle exceptions. Working with exceptions is of course important to Jython, but it is also an important step to
working with Java classes and the exceptions they may raise.

Java does not have functions, but they are an important part of Jython. Chapter 4, "User-Defined Functions and
Variable Scoping," shows how to define and use Jython functions and how to use Jython's functional programming
tools. Functions are callable objects not defined within a class, but functional programming has a less succinct
definition. Functional programming revolves around finding the results of an expression. Jython supplies all the tools
required to learn and use functional programming, and these tools appear in Chapter 2.

Jython has modules, another unit that Java does not have, and Chapter 5, "Modules and Packages," describes
Jython's modules. Jython also has packages, as does Java, but Jython packages differ from the Java counterpart as
Chapter 5 explains. With Jython packages, modules, and classes as well as Java packages and classes, the details of
the import statement quickly become important. Chapter 5 clarifies the import statement along with modules and
packages.

Chapter 6, "Classes, Instances, and Inheritance," introduces the definition and use of Jython classes. This includes the
subclassing of Java classes, the use of Java interfaces and Java abstract classes, and the implications of Java's access
modifiers such as public, private, and protected. Jython classes do differ from Java classes, however, and Chapter 6
clarifies these differences.
Chapter 7, "Advanced Classes," extends the information on Jython classes to include Jython's special class attributes.
Special attributes in Jython are those that follow a special naming convention and provide specific functionality. These
special attributes let you customize a class's behavior and makes creating advanced classes relatively easy.

Chapter 8, "Compiling Jython with jythonc jythonc," details Jython's complicated jythonc tool. jythonc compiles
Jython code to Java byte-code. jythonc lets you use classes written in Jython within Java frameworks, and even lets
you create class files that you can import and use from within Java.

Chapter 9, "Embedding and Extending Jython in Java," describes how to embed a Jython interpreter. Compiling
Jython to Java byte-code is extremely useful, but embedding a Jython interpreter within Java applications has many
advantages. Embedding gives you total control over Jython's system state and allows you to use all of Jython's
features and modules within a Java application. The amazing part is how simple it is to embed a Jython interpreter. A
basic embedded interpreter requires only two lines of Java code, and adding additional configuration to an embedded
interpreter is equally easy. An embedded interpreter allows you to write Jython modules to extend or implement
features of Java applications without having to compile modules with jythonc. It is my impression that embedding
Jython is the foremost advantage of Jython. It allows multi-level language development, leverages all that is good in
Java and Python within a single application, and allows rapid development and extensibility. There is already a
number of projects that embed Jython, and the trend to do so will likely continue.

Chapter 10, "GUI Development," describes how to develop graphical applications with Jython. The focus is on
Java's Abstract Windowing Toolkit (AWT) and Swing application programmer's interface. Jython allows rapid
development of graphical applications because of its addition of automatic bean properties and events. Chapter 10
covers the details of automatic bean properties and events, but the basic idea is that Jython automatically searches a
component for these features and adds shortcuts to establishing properties and event handlers. The shortcuts leverage
Jython syntax features to simplify and accelerate development. Chapter 10 also includes information on creating Java
applets with Jython.

Java has become very prominent in database programming, and Jython is able to leverage all of Java's success in this
area while adding its own advantages. Chapter 11, "Database Programming," introduces the use of Jython in
database programming. Chapter 11 includes information on hashed database files as well as the MySQL and
PostgreSQL relation database management systems (object-relation for PostgreSQL). Jython also has the advantage
of being able to use Java's JDBC database connectivity or the Python database application programmer's interface
implemented with zxJDBC. Chapter 11 discusses both of these APIs.

Chapter 12, "Server-Side Web Programming," describes web programming with Jython. For Jython, this means
servlets, Java Server Pages (JSP), and taglibs. In other words, server-side web development with Jython coincides
with the popular (standard) Java web development paradigm. Chapter 12 addresses using jythonc -compiled classes
as servlets as well as an embedded Jython Servlet mapping and IBM's bean scripting framework (BSF).

Who This Book Is For

This book best fits those programmers already familiar with Java but who are interested Jython. This creates a wide
range of potential readers, and further clarification follows to help narrow the field. Java programmers wishing to add
a high-level language as a tool in their existing arsenal is the primary audience, but is equally applicable to those
seeking an alternative to Java, yet bound to an organization dedicated to Java-based technology. A secondary
audience is those beginning Python programmers wishing to extent their Python facility within Java frameworks.
Because this book assumes some knowledge of Java basics, this secondary audience may require an additional
source for Java fundamentals.
A distant tertiary audience would be those new to programming, but this requires careful qualification. This book
alone is insufficient as an introduction to programming. At a minimum, an additional resource on the fundamentals of
Java is required. The reason that this is a reasonable view is that Jython (and Python) is an ideal learning language.
The Python language embodies clarity and simplicity while its interactive interpreter allows experimentation,
immediate feedback, and rapid acquisition of language features. The fact that Jython supports functional programming
as well as object-oriented programming is an educational advantage.

Who This Book Isn't For

If you have no interest in Java, then this book is not for you. Jython requires an understanding of Java, and those who
do not know Java, or do not intent to pursue it in parallel with this book, will not benefit from this book. The
advantage of Jython is its ability to masquerade as Java and to seamlessly use Java libraries. This means the absence
of a basic conviction to Java-centric tools makes Jython, and this book, a poor choice for your needs.

If you are already an advanced Python programmer, this book may not be for you. A substantial portion of this book
is Python syntax and usage. Java-specific examples and information do appear, but only within larger sections on
syntax and usage that an experienced Python program may find too repetitious.

Additional Resources

Jython-related Internet resources, and the reason for their significance, are listed in this section.

http://www.jython.org/ Jython's official home page.


http://www.python.org/ Python's official home page. Python has a great collection of documentation available
at this site that is also applicable to Jython.

http://www.digisprings.com/jython/ The website associated with this book.You will find additional Jython
information, as well as book errata, tips, and more at this site.

http://sourceforge.net/projects/zxjdbc This is the project page for the zxJDBC package. This package
provides Python 2.0 database functionality for Jython.

Mailing lists specific to Jython are a valuable resource. It is best to subscribe to such lists from the links available on
Jython's home page, and the lists available are jython-users, jython-dev, and jython-announce. The jython-users list is
designed for general Jython questions and help, whereas the jython-dev list is for matters related to the development
of Jython itself (as opposed to development with Jython). The announce list is a low-volume list designed to keep
users posted about new releases. If you face problems that are not addressed in the book, at
http://www.newriders.com/, or at the Jython website, it is best to consult the mailing lists.
Jython for Java Programmers
By Robert W. Bill

Publisher: New Riders Publishing


Pub Date: December 21, 2001
ISBN: 0-7357-1111-9
Table Pages: 500
of

Content Jython for Java Programmers is an indispensable guide for Java developers
s wishing to accelerate development and increase flexibility using Jython. Jython
itself is the marriage of Java and the increasingly popular high-level programming
language Python. Not only is this book a concise guide to Jython, it is also one
of the most complete guides currently available on integrating Python with the
Java development platform.

Copyright
777
About the Author
About the Technical Reviewers
Acknowledgments
Tell Us What You Think
Introduction
What Is Jython?
Why Jython?
What You Can Expect from This Book
Additional Resources

Part I: Jython
Chapter 1. Jython Syntax, Statements, and Comments
The Interactive Console
Line Separators and Block Indentation Syntax
Comments
Documentation Strings
Statements
Comparing Jython and Java

Chapter 2. Operators, Types, and Built-In Functions


Identifiers
Jython Data Objects
Operators
Built-Ins
Comparison of Jython Data Types and Java Data Types
Java Types

Chapter 3. Errors and Exceptions


Jython Exceptions
Exception Handling
The raise Statement
Tracebacks
The assert Statement and the __debug__ Variable
The Warnings Framework
Comparing Jython and Java
Chapter 4. User-Defined Functions and Variable Scoping
Defining Functions
Namespaces
Recursion
Built-In Functional Programming Tools
Synchronization

Chapter 5. Modules and Packages


The import Statement
A Comparison of Jython and Java
Python's package.module Hierarchy
Java's package.class Hierarchy
Reloading

Chapter 6. Classes, Instances, and Inheritance


Encapsulation, Abstraction, and Information Hiding
Defining Jython Classes
Jython Class and Instance Attributes
Constructors
Finalizer or Destructor
Inheritance
Method Overloading
Sample Classes

Chapter 7. Advanced Classes


Pre-Existing Class Attributes
Pre-Existing Instance Attributes
Special Methods for General Customization
Dynamic Attribute Access
The Callable Hook—__call__
Special Comparison Methods
Object "Truth"
Emulating Built-In Data Objects

Part II: Jython Internals and Integrating Jython With Java


Chapter 8. Compiling Jython with jythonc
What Is jythonc?
Compiling a Module with jythonc
Paths and Compiled Jython
jythonc Options
Java-Compatible Classes

Chapter 9. Embedding and Extending Jython in Java


Embedding Jython
Embedding the InteractiveInterpreter
Embedding an InteractiveConsole
Extending Jython

Part III: Applications with Jython


Chapter 10. GUI Development
Comparing a Java and Jython GUI
Bean Properties and Events
The pawt Package
Examples

Chapter 11. Database Programming


DBM Files
Serialization
Database Management Systems
JDBC
zxJDBC

Chapter 12. Server-Side Web Programming


Jython Servlet Containers
Defining Simple Servlet Classes
More About GenericServlet
HttpServlet
PyServlet
Cookies
Sessions
Databases and Servlets
JSP

Part IV: Appendix


Appendix A. Jython Statements and Built-In Functions Quick Reference

Copyright

Copyright © 2002 by New Riders Publishing

FIRST EDITION: December, 2001

All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic
or mechanical, including photocopying, recording, or by any information storage and retrieval system, without written
permission from the publisher, except for the inclusion of brief quotations in a review.

Library of Congress Catalog Card Number: 00-111656

06 05 04 03 02 7 6 5 4 3 2 1

Interpretation of the printing code: The rightmost double-digit number is the year of the book's printing; the rightmost
single-digit number is the number of the book's printing. For example, the printing code 02-1 shows that the first
printing of the book occurred in 2002.

Composed in Quark and MCPdigital by New Riders Publishing.

Printed in the United States of America.


Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately
capitalized. New Riders Publishing cannot attest to the accuracy of this information. Use of a term in this book should
not be regarded as affecting the validity of any trademark or service mark.

Warning and Disclaimer

This book is designed to provide information about Jython. Every effort has been made to make this book as
complete and as accurate as possible, but no warranty or fitness is implied.

The information is provided on an as-is basis. The authors and New Riders Publishing shall have neither liability nor
responsibility to any person or entity with respect to any loss or damages arising from the information contained in this
book or from the use of the discs or programs that may accompany it.

Credits

Publisher

David Dwyer

Associate Publisher

Stephanie Wall

Production Manager

Gina Kanouse

Managing Editor

Kristy Knoop

Senior Development Editor

Lisa M. Thibault
Project Editor

Todd Zellers

Product Marketing Manager

Stephanie Layton

Publicity Manager

Susan Nixon

Copy Editor

Daryl Kessler

Indexer

Chris Morris

Manufacturing Coordinator

Jim Conway

Book Designer

Louisa Klucznik

Cover Designer

Brainstorm Design, Inc.

Cover Production

Aren Howell

Proofreader
Katherine Shull

Composition

Jeff Bredensteiner

Amy Parker

Dedication

To my wife

About the Author

Robert W. Bill currently dedicates his time to software design and development in Python, Jython, and Java as an
independent contractor. His experiences include a four-year tenure with the Minnesota Educational Computing
Consortium, The Learning Company, and Mattel. Robert has studied at Baylor University, followed by various
courses in music and sciences at the Eastman School of Music and the University of Wisconsin-Madison.

About the Technical Reviewers

These reviewers contributed their considerable hands-on expertise to the entire development process for Jython for
Java Programmers. As the book was being written, these dedicated professionals reviewed all the material for
technical content, organization, and flow. Their feedback was critical to ensuring that Jython for Java Programmers
fits our reader's need for the highest quality technical information.
As member of the research staff at the California Institute of Technology, Dr. Robert Brunner focuses on Knowledge
Discovery and Data-Mining in very large, heavily distributed databases. He also has been a Java and XML instructor
at the Center for Advanced Computing Technology operated by the California State Polytechnic University at
Pomona for the last two years. Recently, he has written a series for Java Developers Journal, reviewed numerous
proposals for a variety of publishing houses, and has edited texts covering Linux, C++, Java, and XML. He is
currently completing Enterprise Java Database Programming to be published by Addison Wesley, Inc.

John Ha is a support engineer and technical writer at NeTraverse, a software development firm in Morrisville, North
Carolina. John is responsible for printed and online documentation for the firm's flagship product, Win4Lin. Win4Lin
allows Microsoft Windows to be installed on a host Linux system. John also investigates distributed filesystem and
remote display technologies for NeTraverse's server product currently under development. John earned his Bachelor
of Arts degree in English Literature from the University of Connecticut in Storrs, Connecticut.

Acknowledgments

Those who work to refine and support Jython prove themselves invaluable day after day. Most notable is Finn Bock,
the Jython project leader. His work currently propels Jython's rapid advance. Other valuable contributors to Jython
and its online community who have helped me in one way or another include Samuele Pedroni, Brian Zimmer, Barry
Warsaw, and many others.

Tell Us What You Think

As the reader of this book, you are the most important critic and commentator. We value your opinion and want to
know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other
words of wisdom you're willing to pass our way.

As the Associate Publisher for New Riders Publishing, I welcome your comments. You can fax, email, or write me
directly to let me know what you did or didn't like about this book—as well as what we can do to make our books
stronger.

Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high
volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book's title and author as well as your name and phone or fax number.
I will carefully review your comments and share them with the author and editors who worked on the book.
Fax: 317-581-4663

Email: nrfeedback@newriders.com

Mail: Stephanie Wall


Associate Publisher
New Riders Publishing
201 West 103rd Street
Indianapolis, IN 46290 USA

Introduction

Jython is the combination of two programming languages—Java and Python—that have achieved tremendous
popularity separately. Java has tremendous acceptance, as evidenced by the number of organizations that deploy
Java-specific applications. Additionally, Java has a huge library of classes to draw from and excellent documentation.
However, Python provides such flexibility, speedy development, and a sense of ease. Choosing between two such
languages would be difficult but, fortunately, is unnecessary thanks to Jython. With Jython, you may implement any
class, algorithm, and pattern in Java or Python without regard for the other language, yet maintain near-seamless
operation between the two languages.

The word seamless is of special significance and recurs throughout this book. Extending other languages, like Perl or
Python, requires the use of a specific API, or annoying wrapper classes. Arbitrary C code will not work in Perl or
Python without additional effort, but arbitrary Java code will work in Jython. Because of the seamless integration with
Java, you can import, use, and even subclass any Java class in Jython. Not just those classes written to follow a
specific API, or those wrapped with special tools, but any Java class. Furthermore, you can compile Jython into Java
byte-code that runs in Java frameworks. You can even import, use, and subclass Python classes from within Java.

Any minor seams that do exist are required to negotiate the differences between Jython and Java, and understanding
such differences helps in understanding Jython. Java is a type-rich language with static typing, whereas Jython uses
dynamic types without explicit type declarations. Java has packages that contain classes, while Jython has packages,
modules, classes, and functions. Java must be compiled, but Jython can run interactively, interpret an uncompiled
script, or be compiled to byte-code. Java classes implement access modifiers such as private and protected; Jython
has only minimal access restrictions and no explicit modifiers like private.

The interesting thing about the differences between Java and Jython is that rather than creating difficulties, these
languages make for ideal complements. Jython's interactive mode is a quick way to test and explore Java classes,
whereas Java's interfaces and abstract classes are a great way to specify protocols for Jython subclasses. Jython's
dynamic typing helps in rapid prototyping and flexibility, while Java's static typing allows for increased runtime
efficiency and type safety. This complement excels because it is seamless. Adding programming overhead to leverage
each of these features would negate their power; fortunately, Jython makes leveraging them intuitive, easy, and free
from detracting overhead.

What Is Jython?

Defining Jython begs the question "What is Python?" Python is a high-level, object-oriented, open-source
programming language implemented in C. Guido Van Rossum was the original developer of Python and continues to
guide a hoard of leading designers and programmers in Python's rapid evolution. The number of developers using
Python has grown rapidly, and continues to do so. However, the advance of Sun's Java programming language is
equally pervasive in the programming landscape. With the number of projects implemented in Java approaching those
in C/C++, there became a need for a Java implementation of Python. Jython, originally called JPython, is just that: the
Java implementation of the Python programming language. To eliminate confusion, this book uses CPython to signify
the C implementation of Python, Jython to signify the Java implementation, and Python to represent the
implementation neutral concepts and design features of the Python language specification.

Jython is a complete programming language—not a Java translator and not just a Python compiler, but a complete
implementation of Python in Java. You can write complete complex applications with Jython itself. Jython also has a
sizable library of modules inherited from CPython. The interesting thing is that Jython, unlike CPython and many other
high-level languages, gives you access to everything it its implementation language, Java. So not only does Jython give
you the Python libraries, it also gives you all available Java classes. This makes for a truly large library of resources.

Jython, and Python, emphasizes code clarity, simplicity, and legibility. Jython uses indentation to delimit code blocks
to avoid the braces found in Java. Jython uses a newline to denote the beginning of a new statement, with a few
important exceptions, allowing for the elimination of a semicolon at the end of each statement. Jython foregoes
attribute access modifiers such as Java's public, private, and protected, giving the programmer the flexibility required
for rapid development and to focus on program logic. And as mentioned earlier, Jython does not use explicit static
typing, so there are no type declarations to distract from program logic.

Jython's history begins with Jim Hugunin, a colleague of Guido Van Rossum at the Center for National Research
Incentives (CNRI), who recognized the need for a Java implementation of the Python programming language and
implemented it under the original name JPython. Eventually, Jim Hugunin was unable to continue working on JPython
because of an opportunity to develop aspectj (http://aspectj.org/). Therefore, Barry Warsaw, also at CNRI at that
time, continued as the project leader during a time when Python developers were preparing to move away from
CNRI.

The move away from CNRI was a transition toward the more open development model at Sourceforge where the
Python and Jython projects currently reside. During this time, Finn Bock, a major contributor to Jython (JPython),
took the reins of the Jython project. It is in a very large part due to Finn Bock's extremely prolific and quality
additions to Jython that it has become such a valuable tool. Open-source projects like Jython excel only as much as
those that develop and maintain them, and Jython has proven to be most fortunate in this regard because of Finn
Bock's contributions and guidance. Another more recent and valuable contributor to Jython is Samuele Pedroni.
Recent advancements in Jython's classloading, import mechanisms, and more is thanks to Samuele's contributions.
Finn and Samuele are currently the two primary developers of Jython.

Why Jython?

Jython is unique in that it inherits the desirable traits of both Java and Python. The sections that follow describe each
of the traits and their benefits.

Seamless Access to Java Classes

Implementing Python in Java makes for an interesting look at the usefulness of Java's Reflection API. Reflection
allows Jython to seamlessly use most any Java class. Jython inherits a number of advantages from CPython, but
CPython has a bump between C and Python that restricts the usefulness of C libraries other than those specifically
written for Python. Eliminating this bump in Jython truly has an impact of productivity and effectiveness.

Because of the seamless fit with Java, Jython can benefit any organization that deploys Java applications and
frameworks without any additional work. Adopting another development language is a monumental and weighty
decision for most organizations because of the implications for frameworks, servers, and peripheral tools. Jython,
however, seamlessly masquerades as Java, making it but a seamless addition to an existing Java repertoire rather than
a weighty decision. This is not the case for other high-level languages. A vast number of organizations have towering
investments in Java that reduce the benefit, or at least the appeal, of CPython, Perl, Ruby, PHP, and other high-level
languages that do not transparently leverage existing Java implementations. Jython, on the other hand, is a powerful
complement to existing Java frameworks that blends in transparently.

Efficiency

A fair calculation of efficiency is a broad topic that must account for programmer time, total complexity, lines of code,
reusability, maintainability, and runtime efficiency. Of course, many people disagree on the weight assigned to these
variables, and more often than not the situation at hand dictates which is favored in the calculation; however, it is the
premise of this book that Jython exceeds other languages in all areas but runtime efficiency. Jython's runtime speed
compares well with other high-level languages, but speed is never the goal or advantage of a high-level language. The
difference, however, is that when accelerating an application is required it is easier to translate Jython code into Java
because of Jython's seamless integration with Java. Additionally, the direct access to all available Java classes
increases the likelihood of leveraging existing classes.

Dynamic Types

You do not declare types in Jython as you would in Java because types are determined at runtime. Jython's list and
mapping types are high-level, polymorphic objects that are instances of Java classes. Polymorphic means that an
object works for differing types of data. Jython's list type, for example, can be a sequence of numbers, strings,
characters, or a combination of types. Dynamic and polymorphic types are a dramatic contribution to programmer
efficiency, reduced lines of code, and reduced complexity, as evidenced in numerous high-level languages that forgo
explicit, static, and primitive types.

Introspection and Dynamic Execution

Jython has built-in functions that allow easy object introspections and dynamic execution of code. Introspection is the
ability to discover information about an object, while dynamic execution is the ability to execute code that is
generated at runtime.This functionality dramatically reduces lines of code and programmer efficiency while easing
maintainability.This also allows a close integration of data and program structure or logic without affecting reusability
because everything is determined at runtime.

First-Class Functions and Functional Programming

Jython, as does Python, has first-class functions. A first-class function is a callable object that can be passed around
like any variable. First-class functions are valuable to event handling and many other situations, leading to Java's
addition of inner classes. Although Java's inner classes are similar to first-class functions, they do not compare with
the ease and flexibility of using Jython's first-class functions because of the reduced syntax overhead in Jython.

Jython also includes all the tools required for functional programming.This means that imperative, object-oriented,
and functional programming approaches are supported in Jython.This is obviously an educational advantage, but it
also allows a Jython programmer to choose the paradigm most appropriate to the situation rather than that imposed
by the language. Functional tools such as list comprehension, lambda forms, map, filter, and reduce, also can have a
dramatic affect on reducing lines of code, complexity, and the number of name rebindings (name rebindings increase
risk of negative side effects, such as bugs).

Short Learning Curve

Any Java programmer can become proficient in Jython within days. As with many things, the art is in the details, but
the ability to leverage the rapid development capabilities of Jython within only a few days is valuable.The ability to
easily acquire Jython facility in testing and support groups that would not normally have time to study complex Java
code can raise an organization's technical level and efficiency without incurring high training overhead.

Write Once, Run Anywhere

Because Jython is written in Java, and because it compiles into Java byte-code, Jython also benefits from Java's
"write once, run anywhere" approach. Jython runs on any platform with a compliant Java 1.1 or greater Java Virtual
Manager ( JVM). Additionally, you can fully compile Jython applications into byte-code that is fully self-sufficient,
and can run on any complaint JVM. Applications compiled on Linux will run on any other platform with a compliant
JVM.

Java Security

Java's security is exceptional, and increasingly important. From sandbox to signatures, Jython has the potential to use
Java's truly exceptional security framework.

Code Clarity

Code clarity is the Holy Grail of Python, and of course Jython. Unnecessary punctuation and line noise is avoided.
Jython code should approach natural language in legibility and clarity.This begins with Python's commitment to
whitespace delineation of code blocks and statements. Indentation marks code blocks and new lines mark new
statements. Beyond that, the syntax is always chosen to favor clarity. Maintaining Jython code is easier because it is
more clear.

Unicode and Internationalization

Jython uses Java's unicode implementation, allowing for easy implementation of international products.

Hotspot and Development Efficiency

Jython's speed is reasonable, but not as fast as pure Java.The major advantages to Jython are in development and
maintenance time; however, multi-level language development has strong precedence, most notable in Java's Hotspot
technology. Hotspot optimizes those sections of a program that are in most need of optimization. The theory is that
only a small portion of a program incurs a large portion of its execution time. Only optimizing those portions of code
that have a large effect on performance makes the most sense. Doing the same when developing the code is equally
sensible. Using Jython to write an application and then converting processor-intensive classes to Java is the ideal
combination of runtime performance and programmer efficiency. The Hotspot analogy makes multi-level language
development with Jython and Java a convincing development model.

What You Can Expect from This Book

This book is designed for those who know Java or are learning Java. The Java-specific meaning of terms such as
classpath, garbage collection, and interface appear without explanation, but no more than rudimentary Java
knowledge is required. Specifically, Java developers desiring accelerated development, embedded interpreters, and
increased flexibility will most appreciate this book. Although Jython is a complete programming language, it is unique
in its ability to complement Java development rather than appear as an alternative to Java.

Chapter 1, "Jython Syntax, Statements, and Comments," introduces syntax and statements. Python's syntax is an
essential part of what constitutes the coined word pythonic, an important descriptor of those details that make Python
and Jython code clear, simple, and distinct. Python's use of indentation to delimit code blocks and newlines to delimit
statements is new to most programmers, and Chapter 1 details the rules that apply to indentation, newlines, and
statements. Additionally, Chapter 1 introduces the interactive interpreter, a Jython mode that immediately evaluates
statements as you enter them.This chapter applies to Python in general with no references to material unique to Jython.

Chapter 2, "Operators, Types, and Built-In Functions," covers Jython's data object, operators, and built-in functions.
Data objects, or types, are especially interesting because of Jython's ability to use both Python and Java objects. The
Python language specification defines Python's, and therefore Jython's types, but types are where Jython-specific
details emerge. One such detail is the conversion between Jython and Java types. Chapter 2 also defines Jython's
built-in functions, which are those functions that are available without any import statements and that account for a
sizable portion of Jython's functionality.

Jython's errors, exceptions, and warnings appear in Chapter 3, "Errors and Exceptions." Chapter 3 contains the
definitions of Jython's built-in exceptions as well as a detailed look at the try/except and try/finally statements used to
handle exceptions. Working with exceptions is of course important to Jython, but it is also an important step to
working with Java classes and the exceptions they may raise.

Java does not have functions, but they are an important part of Jython. Chapter 4, "User-Defined Functions and
Variable Scoping," shows how to define and use Jython functions and how to use Jython's functional programming
tools. Functions are callable objects not defined within a class, but functional programming has a less succinct
definition. Functional programming revolves around finding the results of an expression. Jython supplies all the tools
required to learn and use functional programming, and these tools appear in Chapter 2.

Jython has modules, another unit that Java does not have, and Chapter 5, "Modules and Packages," describes
Jython's modules. Jython also has packages, as does Java, but Jython packages differ from the Java counterpart as
Chapter 5 explains. With Jython packages, modules, and classes as well as Java packages and classes, the details of
the import statement quickly become important. Chapter 5 clarifies the import statement along with modules and
packages.

Chapter 6, "Classes, Instances, and Inheritance," introduces the definition and use of Jython classes. This includes the
subclassing of Java classes, the use of Java interfaces and Java abstract classes, and the implications of Java's access
modifiers such as public, private, and protected. Jython classes do differ from Java classes, however, and Chapter 6
clarifies these differences.
Chapter 7, "Advanced Classes," extends the information on Jython classes to include Jython's special class attributes.
Special attributes in Jython are those that follow a special naming convention and provide specific functionality. These
special attributes let you customize a class's behavior and makes creating advanced classes relatively easy.

Chapter 8, "Compiling Jython with jythonc jythonc," details Jython's complicated jythonc tool. jythonc compiles
Jython code to Java byte-code. jythonc lets you use classes written in Jython within Java frameworks, and even lets
you create class files that you can import and use from within Java.

Chapter 9, "Embedding and Extending Jython in Java," describes how to embed a Jython interpreter. Compiling
Jython to Java byte-code is extremely useful, but embedding a Jython interpreter within Java applications has many
advantages. Embedding gives you total control over Jython's system state and allows you to use all of Jython's
features and modules within a Java application. The amazing part is how simple it is to embed a Jython interpreter. A
basic embedded interpreter requires only two lines of Java code, and adding additional configuration to an embedded
interpreter is equally easy. An embedded interpreter allows you to write Jython modules to extend or implement
features of Java applications without having to compile modules with jythonc. It is my impression that embedding
Jython is the foremost advantage of Jython. It allows multi-level language development, leverages all that is good in
Java and Python within a single application, and allows rapid development and extensibility. There is already a
number of projects that embed Jython, and the trend to do so will likely continue.

Chapter 10, "GUI Development," describes how to develop graphical applications with Jython. The focus is on
Java's Abstract Windowing Toolkit (AWT) and Swing application programmer's interface. Jython allows rapid
development of graphical applications because of its addition of automatic bean properties and events. Chapter 10
covers the details of automatic bean properties and events, but the basic idea is that Jython automatically searches a
component for these features and adds shortcuts to establishing properties and event handlers. The shortcuts leverage
Jython syntax features to simplify and accelerate development. Chapter 10 also includes information on creating Java
applets with Jython.

Java has become very prominent in database programming, and Jython is able to leverage all of Java's success in this
area while adding its own advantages. Chapter 11, "Database Programming," introduces the use of Jython in
database programming. Chapter 11 includes information on hashed database files as well as the MySQL and
PostgreSQL relation database management systems (object-relation for PostgreSQL). Jython also has the advantage
of being able to use Java's JDBC database connectivity or the Python database application programmer's interface
implemented with zxJDBC. Chapter 11 discusses both of these APIs.

Chapter 12, "Server-Side Web Programming," describes web programming with Jython. For Jython, this means
servlets, Java Server Pages (JSP), and taglibs. In other words, server-side web development with Jython coincides
with the popular (standard) Java web development paradigm. Chapter 12 addresses using jythonc -compiled classes
as servlets as well as an embedded Jython Servlet mapping and IBM's bean scripting framework (BSF).

Who This Book Is For

This book best fits those programmers already familiar with Java but who are interested Jython. This creates a wide
range of potential readers, and further clarification follows to help narrow the field. Java programmers wishing to add
a high-level language as a tool in their existing arsenal is the primary audience, but is equally applicable to those
seeking an alternative to Java, yet bound to an organization dedicated to Java-based technology. A secondary
audience is those beginning Python programmers wishing to extent their Python facility within Java frameworks.
Because this book assumes some knowledge of Java basics, this secondary audience may require an additional
source for Java fundamentals.
A distant tertiary audience would be those new to programming, but this requires careful qualification. This book
alone is insufficient as an introduction to programming. At a minimum, an additional resource on the fundamentals of
Java is required. The reason that this is a reasonable view is that Jython (and Python) is an ideal learning language.
The Python language embodies clarity and simplicity while its interactive interpreter allows experimentation,
immediate feedback, and rapid acquisition of language features. The fact that Jython supports functional programming
as well as object-oriented programming is an educational advantage.

Who This Book Isn't For

If you have no interest in Java, then this book is not for you. Jython requires an understanding of Java, and those who
do not know Java, or do not intent to pursue it in parallel with this book, will not benefit from this book. The
advantage of Jython is its ability to masquerade as Java and to seamlessly use Java libraries. This means the absence
of a basic conviction to Java-centric tools makes Jython, and this book, a poor choice for your needs.

If you are already an advanced Python programmer, this book may not be for you. A substantial portion of this book
is Python syntax and usage. Java-specific examples and information do appear, but only within larger sections on
syntax and usage that an experienced Python program may find too repetitious.

Additional Resources

Jython-related Internet resources, and the reason for their significance, are listed in this section.

http://www.jython.org/ Jython's official home page.


http://www.python.org/ Python's official home page. Python has a great collection of documentation available
at this site that is also applicable to Jython.

http://www.digisprings.com/jython/ The website associated with this book.You will find additional Jython
information, as well as book errata, tips, and more at this site.

http://sourceforge.net/projects/zxjdbc This is the project page for the zxJDBC package. This package
provides Python 2.0 database functionality for Jython.

Mailing lists specific to Jython are a valuable resource. It is best to subscribe to such lists from the links available on
Jython's home page, and the lists available are jython-users, jython-dev, and jython-announce. The jython-users list is
designed for general Jython questions and help, whereas the jython-dev list is for matters related to the development
of Jython itself (as opposed to development with Jython). The announce list is a low-volume list designed to keep
users posted about new releases. If you face problems that are not addressed in the book, at
http://www.newriders.com/, or at the Jython website, it is best to consult the mailing lists.
Jython for Java Programmers
By Robert W. Bill

Publisher: New Riders Publishing


Pub Date: December 21, 2001
ISBN: 0-7357-1111-9
Table Pages: 500
of

Content Jython for Java Programmers is an indispensable guide for Java developers
s wishing to accelerate development and increase flexibility using Jython. Jython
itself is the marriage of Java and the increasingly popular high-level programming
language Python. Not only is this book a concise guide to Jython, it is also one
of the most complete guides currently available on integrating Python with the
Java development platform.

Copyright
777
About the Author
About the Technical Reviewers
Acknowledgments
Tell Us What You Think
Introduction
What Is Jython?
Why Jython?
What You Can Expect from This Book
Additional Resources

Part I: Jython
Chapter 1. Jython Syntax, Statements, and Comments
The Interactive Console
Line Separators and Block Indentation Syntax
Comments
Documentation Strings
Statements
Comparing Jython and Java

Chapter 2. Operators, Types, and Built-In Functions


Identifiers
Jython Data Objects
Operators
Built-Ins
Comparison of Jython Data Types and Java Data Types
Java Types

Chapter 3. Errors and Exceptions


Jython Exceptions
Exception Handling
The raise Statement
Tracebacks
The assert Statement and the __debug__ Variable
The Warnings Framework
Comparing Jython and Java
Chapter 4. User-Defined Functions and Variable Scoping
Defining Functions
Namespaces
Recursion
Built-In Functional Programming Tools
Synchronization

Chapter 5. Modules and Packages


The import Statement
A Comparison of Jython and Java
Python's package.module Hierarchy
Java's package.class Hierarchy
Reloading

Chapter 6. Classes, Instances, and Inheritance


Encapsulation, Abstraction, and Information Hiding
Defining Jython Classes
Jython Class and Instance Attributes
Constructors
Finalizer or Destructor
Inheritance
Method Overloading
Sample Classes

Chapter 7. Advanced Classes


Pre-Existing Class Attributes
Pre-Existing Instance Attributes
Special Methods for General Customization
Dynamic Attribute Access
The Callable Hook—__call__
Special Comparison Methods
Object "Truth"
Emulating Built-In Data Objects

Part II: Jython Internals and Integrating Jython With Java


Chapter 8. Compiling Jython with jythonc
What Is jythonc?
Compiling a Module with jythonc
Paths and Compiled Jython
jythonc Options
Java-Compatible Classes

Chapter 9. Embedding and Extending Jython in Java


Embedding Jython
Embedding the InteractiveInterpreter
Embedding an InteractiveConsole
Extending Jython

Part III: Applications with Jython


Chapter 10. GUI Development
Comparing a Java and Jython GUI
Bean Properties and Events
The pawt Package
Examples

Chapter 11. Database Programming


DBM Files
Serialization
Database Management Systems
JDBC
zxJDBC

Chapter 12. Server-Side Web Programming


Jython Servlet Containers
Defining Simple Servlet Classes
More About GenericServlet
HttpServlet
PyServlet
Cookies
Sessions
Databases and Servlets
JSP

Part IV: Appendix


Appendix A. Jython Statements and Built-In Functions Quick Reference

Copyright

Copyright © 2002 by New Riders Publishing

FIRST EDITION: December, 2001

All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic
or mechanical, including photocopying, recording, or by any information storage and retrieval system, without written
permission from the publisher, except for the inclusion of brief quotations in a review.

Library of Congress Catalog Card Number: 00-111656

06 05 04 03 02 7 6 5 4 3 2 1

Interpretation of the printing code: The rightmost double-digit number is the year of the book's printing; the rightmost
single-digit number is the number of the book's printing. For example, the printing code 02-1 shows that the first
printing of the book occurred in 2002.

Composed in Quark and MCPdigital by New Riders Publishing.

Printed in the United States of America.


Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately
capitalized. New Riders Publishing cannot attest to the accuracy of this information. Use of a term in this book should
not be regarded as affecting the validity of any trademark or service mark.

Warning and Disclaimer

This book is designed to provide information about Jython. Every effort has been made to make this book as
complete and as accurate as possible, but no warranty or fitness is implied.

The information is provided on an as-is basis. The authors and New Riders Publishing shall have neither liability nor
responsibility to any person or entity with respect to any loss or damages arising from the information contained in this
book or from the use of the discs or programs that may accompany it.

Credits

Publisher

David Dwyer

Associate Publisher

Stephanie Wall

Production Manager

Gina Kanouse

Managing Editor

Kristy Knoop

Senior Development Editor

Lisa M. Thibault
Project Editor

Todd Zellers

Product Marketing Manager

Stephanie Layton

Publicity Manager

Susan Nixon

Copy Editor

Daryl Kessler

Indexer

Chris Morris

Manufacturing Coordinator

Jim Conway

Book Designer

Louisa Klucznik

Cover Designer

Brainstorm Design, Inc.

Cover Production

Aren Howell

Proofreader
Katherine Shull

Composition

Jeff Bredensteiner

Amy Parker

Dedication

To my wife

About the Author

Robert W. Bill currently dedicates his time to software design and development in Python, Jython, and Java as an
independent contractor. His experiences include a four-year tenure with the Minnesota Educational Computing
Consortium, The Learning Company, and Mattel. Robert has studied at Baylor University, followed by various
courses in music and sciences at the Eastman School of Music and the University of Wisconsin-Madison.

About the Technical Reviewers

These reviewers contributed their considerable hands-on expertise to the entire development process for Jython for
Java Programmers. As the book was being written, these dedicated professionals reviewed all the material for
technical content, organization, and flow. Their feedback was critical to ensuring that Jython for Java Programmers
fits our reader's need for the highest quality technical information.
As member of the research staff at the California Institute of Technology, Dr. Robert Brunner focuses on Knowledge
Discovery and Data-Mining in very large, heavily distributed databases. He also has been a Java and XML instructor
at the Center for Advanced Computing Technology operated by the California State Polytechnic University at
Pomona for the last two years. Recently, he has written a series for Java Developers Journal, reviewed numerous
proposals for a variety of publishing houses, and has edited texts covering Linux, C++, Java, and XML. He is
currently completing Enterprise Java Database Programming to be published by Addison Wesley, Inc.

John Ha is a support engineer and technical writer at NeTraverse, a software development firm in Morrisville, North
Carolina. John is responsible for printed and online documentation for the firm's flagship product, Win4Lin. Win4Lin
allows Microsoft Windows to be installed on a host Linux system. John also investigates distributed filesystem and
remote display technologies for NeTraverse's server product currently under development. John earned his Bachelor
of Arts degree in English Literature from the University of Connecticut in Storrs, Connecticut.

Acknowledgments

Those who work to refine and support Jython prove themselves invaluable day after day. Most notable is Finn Bock,
the Jython project leader. His work currently propels Jython's rapid advance. Other valuable contributors to Jython
and its online community who have helped me in one way or another include Samuele Pedroni, Brian Zimmer, Barry
Warsaw, and many others.

Tell Us What You Think

As the reader of this book, you are the most important critic and commentator. We value your opinion and want to
know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other
words of wisdom you're willing to pass our way.

As the Associate Publisher for New Riders Publishing, I welcome your comments. You can fax, email, or write me
directly to let me know what you did or didn't like about this book—as well as what we can do to make our books
stronger.

Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high
volume of mail I receive, I might not be able to reply to every message.

When you write, please be sure to include this book's title and author as well as your name and phone or fax number.
I will carefully review your comments and share them with the author and editors who worked on the book.
Fax: 317-581-4663

Email: nrfeedback@newriders.com

Mail: Stephanie Wall


Associate Publisher
New Riders Publishing
201 West 103rd Street
Indianapolis, IN 46290 USA

Introduction

Jython is the combination of two programming languages—Java and Python—that have achieved tremendous
popularity separately. Java has tremendous acceptance, as evidenced by the number of organizations that deploy
Java-specific applications. Additionally, Java has a huge library of classes to draw from and excellent documentation.
However, Python provides such flexibility, speedy development, and a sense of ease. Choosing between two such
languages would be difficult but, fortunately, is unnecessary thanks to Jython. With Jython, you may implement any
class, algorithm, and pattern in Java or Python without regard for the other language, yet maintain near-seamless
operation between the two languages.

The word seamless is of special significance and recurs throughout this book. Extending other languages, like Perl or
Python, requires the use of a specific API, or annoying wrapper classes. Arbitrary C code will not work in Perl or
Python without additional effort, but arbitrary Java code will work in Jython. Because of the seamless integration with
Java, you can import, use, and even subclass any Java class in Jython. Not just those classes written to follow a
specific API, or those wrapped with special tools, but any Java class. Furthermore, you can compile Jython into Java
byte-code that runs in Java frameworks. You can even import, use, and subclass Python classes from within Java.

Any minor seams that do exist are required to negotiate the differences between Jython and Java, and understanding
such differences helps in understanding Jython. Java is a type-rich language with static typing, whereas Jython uses
dynamic types without explicit type declarations. Java has packages that contain classes, while Jython has packages,
modules, classes, and functions. Java must be compiled, but Jython can run interactively, interpret an uncompiled
script, or be compiled to byte-code. Java classes implement access modifiers such as private and protected; Jython
has only minimal access restrictions and no explicit modifiers like private.

The interesting thing about the differences between Java and Jython is that rather than creating difficulties, these
languages make for ideal complements. Jython's interactive mode is a quick way to test and explore Java classes,
whereas Java's interfaces and abstract classes are a great way to specify protocols for Jython subclasses. Jython's
dynamic typing helps in rapid prototyping and flexibility, while Java's static typing allows for increased runtime
efficiency and type safety. This complement excels because it is seamless. Adding programming overhead to leverage
each of these features would negate their power; fortunately, Jython makes leveraging them intuitive, easy, and free
from detracting overhead.

What Is Jython?

Defining Jython begs the question "What is Python?" Python is a high-level, object-oriented, open-source
Exploring the Variety of Random
Documents with Different Content
PRINTED BY
WILLIAM BRENDON AND SON, LTD.
PLYMOUTH

Transcriber’s note

Anchors for footnote 33 and 34 were added, after careful


consideration where they should have been.
Some illustrations were slightly moved for reader
convenience, but the bold numbers in the index, leading to
the original pages, were not changed.
In the Index, errors in the alphabetical order were not
corrected. Also in the Index, the item “Moseley” seemed to
contain a footnote, which has been removed because it did
not refer to anything. The original said: “see Plate X, fig. C1”.
A few punctuation errors have been corrected silently. Also
the following corrections were made, on page
134 “Fusillers” changed to “Fusiliers” (Fig. 109)
145 “Sketon” changed to “Skeleton” (Dutch Skeleton Dress)
213 “carboard” changed to “cardboard” (made of cardboard
covered with cloth)
221 “almostly” changed to “almost” (agree almost entirely
with those)
263 “mop” changed to “mob” (Fig 154.), also in the List of
Illustrations
278 “Markan” changed to “Marken” (the women of Marken,
in Holland, may have)
289 “o” changed to “0” (8s. 0d.)
309 “deferentiate” changed to “differentiate” (serve to
differentiate the sisters)
314 “promegranate” changed to “pomegranate” (the flowers
of the pomegranate)
329 “had” changed to “hand” (On the other hand, the fact
that)
369 “Abesses” changed to “Abbesses” (Abbesses, costume
of)
388 “oy” changed to “by” (worn by Punch).
Otherwise the original has been preserved, including
inconsistent spelling and hyphenation.
*** END OF THE PROJECT GUTENBERG EBOOK THE HERITAGE OF
DRESS: BEING NOTES ON THE HISTORY AND EVOLUTION OF
CLOTHES ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using
the method you already use to calculate your applicable
taxes. The fee is owed to the owner of the Project
Gutenberg™ trademark, but he has agreed to donate royalties
under this paragraph to the Project Gutenberg Literary
Archive Foundation. Royalty payments must be paid within 60
days following each date on which you prepare (or are legally
required to prepare) your periodic tax returns. Royalty
payments should be clearly marked as such and sent to the
Project Gutenberg Literary Archive Foundation at the address
specified in Section 4, “Information about donations to the
Project Gutenberg Literary Archive Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return
or destroy all copies of the works possessed in a physical
medium and discontinue all use of and all access to other
copies of Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund


of any money paid for a work or a replacement copy, if a
defect in the electronic work is discovered and reported to
you within 90 days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like