Jython For Java Programmers Bill Robert W pdf download
Jython For Java Programmers Bill Robert W pdf download
download
https://ebookbell.com/product/jython-for-java-programmers-bill-
robert-w-21984506
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
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
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
https://ebookbell.com/product/websphere-application-server-
administration-using-jython-1st-edition-robert-a-gibson-2526986
Jython for Java Programmers
By Robert W. Bill
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
Copyright
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.
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.
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.
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
Lisa M. Thibault
Project Editor
Todd Zellers
Stephanie Layton
Publicity Manager
Susan Nixon
Copy Editor
Daryl Kessler
Indexer
Chris Morris
Manufacturing Coordinator
Jim Conway
Book Designer
Louisa Klucznik
Cover Designer
Cover Production
Aren Howell
Proofreader
Katherine Shull
Composition
Jeff Bredensteiner
Amy Parker
Dedication
To my wife
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.
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.
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
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.
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.
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.
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).
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.
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.
Jython uses Java's unicode implementation, allowing for easy implementation of international products.
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.
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).
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.
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.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
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
Copyright
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.
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.
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.
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
Lisa M. Thibault
Project Editor
Todd Zellers
Stephanie Layton
Publicity Manager
Susan Nixon
Copy Editor
Daryl Kessler
Indexer
Chris Morris
Manufacturing Coordinator
Jim Conway
Book Designer
Louisa Klucznik
Cover Designer
Cover Production
Aren Howell
Proofreader
Katherine Shull
Composition
Jeff Bredensteiner
Amy Parker
Dedication
To my wife
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.
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.
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
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.
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.
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.
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).
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.
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.
Jython uses Java's unicode implementation, allowing for easy implementation of international products.
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.
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).
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.
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.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
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
Copyright
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.
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.
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.
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
Lisa M. Thibault
Project Editor
Todd Zellers
Stephanie Layton
Publicity Manager
Susan Nixon
Copy Editor
Daryl Kessler
Indexer
Chris Morris
Manufacturing Coordinator
Jim Conway
Book Designer
Louisa Klucznik
Cover Designer
Cover Production
Aren Howell
Proofreader
Katherine Shull
Composition
Jeff Bredensteiner
Amy Parker
Dedication
To my wife
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.
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.
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
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.
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.
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.
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).
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.
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.
Jython uses Java's unicode implementation, allowing for easy implementation of international products.
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.
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).
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.
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.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
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
Copyright
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.
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.
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.
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
Lisa M. Thibault
Project Editor
Todd Zellers
Stephanie Layton
Publicity Manager
Susan Nixon
Copy Editor
Daryl Kessler
Indexer
Chris Morris
Manufacturing Coordinator
Jim Conway
Book Designer
Louisa Klucznik
Cover Designer
Cover Production
Aren Howell
Proofreader
Katherine Shull
Composition
Jeff Bredensteiner
Amy Parker
Dedication
To my wife
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.
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.
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
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
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.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.
• 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 comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
ebookbell.com