Screenshot
Jython for Java Programmers

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

777

Screenshot Copyright
    Screenshot About the Author
    Screenshot About the Technical Reviewers
    Screenshot Acknowledgments
    Screenshot Tell Us What You Think
    Screenshot Introduction
      Screenshot What Is Jython?
      Screenshot Why Jython?
      Screenshot What You Can Expect from this tutorial
      Screenshot Additional Resources
   
    Screenshot Part I:  Jython
      Screenshot Chapter 1.  Jython Syntax, Statements, and Comments
      Screenshot The Interactive Console
      Screenshot Line Separators and Block Indentation Syntax
      Screenshot Comments
      Screenshot Documentation Strings
      Screenshot Statements
      Screenshot Comparing Jython and Java
   
      Screenshot Chapter 2.  Operators, Types, and Built-In Functions
      Screenshot Identifiers
      Screenshot Jython Data Objects
      Screenshot Operators
      Screenshot Built-Ins
      Screenshot Comparison of Jython Data Types and Java Data Types
      Screenshot Java Types
   
      Screenshot Chapter 3.  Errors and Exceptions
      Screenshot Jython Exceptions
      Screenshot Exception Handling
      Screenshot The raise Statement
      Screenshot Tracebacks
      Screenshot The assert Statement and the __debug__ Variable
      Screenshot The Warnings Framework
      Screenshot Comparing Jython and Java
   
      Screenshot Chapter 4.  User-Defined Functions and Variable Scoping
      Screenshot Defining Functions
      Screenshot Namespaces
      Screenshot Recursion
      Screenshot Built-In Functional Programming Tools
      Screenshot Synchronization
   
      Screenshot Chapter 5.  Modules and Packages
      Screenshot The import Statement
      Screenshot A Comparison of Jython and Java
      Screenshot Python's package.module Hierarchy
      Screenshot Java's package.class Hierarchy
      Screenshot Reloading
   
      Screenshot Chapter 6.  Classes, Instances, and Inheritance
      Screenshot Encapsulation, Abstraction, and Information Hiding
      Screenshot Defining Jython Classes
      Screenshot Jython Class and Instance Attributes
      Screenshot Constructors
      Screenshot Finalizer or Destructor
      Screenshot Inheritance
      Screenshot Method Overloading
      Screenshot Sample Classes
   
      Screenshot Chapter 7.  Advanced Classes
      Screenshot Pre-Existing Class Attributes
      Screenshot Pre-Existing Instance Attributes
      Screenshot Special Methods for General Customization
      Screenshot Dynamic Attribute Access
      Screenshot The Callable Hook—__call__
      Screenshot Special Comparison Methods
      Screenshot Object "Truth"
      Screenshot Emulating Built-In Data Objects
   
   
    Screenshot Part II:  Jython Internals and Integrating Jython With Java
      Screenshot Chapter 8.  Compiling Jython with jythonc
      Screenshot What Is jythonc?
      Screenshot Compiling a Module with jythonc
      Screenshot Paths and Compiled Jython
      Screenshot jythonc Options
      Screenshot Java-Compatible Classes
   
      Screenshot Chapter 9.  Embedding and Extending Jython in Java
      Screenshot Embedding Jython
      Screenshot Embedding the InteractiveInterpreter
      Screenshot Embedding an InteractiveConsole
      Screenshot Extending Jython
   
   
    Screenshot Part III:  apps with Jython
      Screenshot Chapter 10.  GUI Development
      Screenshot Comparing a Java and Jython GUI
      Screenshot Bean Properties and Events
      Screenshot The pawt Package
      Screenshot Examples
   
      Screenshot Chapter 11.  Database Programming
      Screenshot DBM Files
      Screenshot Serialization
      Screenshot Database Management Systems
      Screenshot JDBC
      Screenshot zxJDBC
   
      Screenshot Chapter 12.  Server-Side Web Programming
      Screenshot Jython Servlet Containers
      Screenshot Defining Simple Servlet Classes
      Screenshot More About GenericServlet
      Screenshot HttpServlet
      Screenshot PyServlet
      Screenshot Cookies
      Screenshot Sessions
      Screenshot Databases and Servlets
      Screenshot JSP
   
   
    Screenshot Part IV:  Appendix
      Screenshot Appendix A.  Jython Statements and Built-In Functions Quick Reference

 

Introduction

Jython is the combination of two coding 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 apps. 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 tutorial. 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 coding 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 coding 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 coding language is equally pervasive in the coding 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 coding language. To eliminate confusion, this tutorial 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 coding language—not a Java translator and not just a Python compiler, but a complete implementation of Python in Java. You can write complete complex apps 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 coding language and implemented it under the original name JPython. Eventually, Jim Hugunin was unable to continue working on JPython because of an opportunity to develop aspectj (http://aspectj.org/). Therefore, Barry Warsaw, also at CNRI at that time, continued as the project leader during a time when Python developers were preparing to move away from CNRI. The move away from CNRI was a transition toward the more open development model at Sourceforge where the Python and Jython projects currently reside. During this time, Finn Bock, a major contributor to Jython (JPython), took the reins of the Jython project. It is in a very large part due to Finn Bock's extremely prolific and quality additions to Jython that it has become such a valuable tool. Open-source projects like Jython excel only as much as those that develop and maintain them, and Jython has proven to be most fortunate in this regard because of Finn Bock's contributions and guidance. Another more recent and valuable contributor to Jython is Samuele Pedroni. Recent advancements in Jython's classloading, import mechanisms, and more is thanks to Samuele's contributions. Finn and Samuele are currently the two primary developers of Jython.

Why Jython?

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

Seamless Access to Java Classes

Implementing Python in Java makes for an interesting look at the usefulness of Java's Reflection API. Reflection allows Jython to seamlessly use most any Java class. Jython inherits a number of advantages from CPython, but CPython has a bump between C and Python that restricts the usefulness of C libraries other than those specifically written for Python. Eliminating this bump in Jython truly has an impact of productivity and effectiveness. Because of the seamless fit with Java, Jython can benefit any organization that deploys Java apps 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 tutorial 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 app is required it is easier to translate Jython code into Java because of Jython's seamless integration with Java. Additionally, the direct access to all available Java classes increases the likelihood of leveraging existing classes.

Dynamic Types

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

Introspection and Dynamic Execution

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

First-Class Functions and Functional Programming

Jython, as does Python, has first-class functions. A first-class function is a callable object that can be passed around like any variable. First-class functions are valuable to event handling and many other situations, leading to Java's addition of inner classes. Although Java's inner classes are similar to first-class functions, they do not compare with the ease and flexibility of using Jython's first-class functions because of the reduced syntax overhead in Jython. Jython also includes all the tools required for functional programming.This means that imperative, object-oriented, and functional coding approaches are supported in Jython.This is obviously an educational advantage, but it also allows a Jython programmer to choose the paradigm most appropriate to the situation rather than that imposed by the language. Functional tools such as list comprehension, lambda forms, map, filter, and reduce, also can have a dramatic affect on reducing lines of code, complexity, and the number of name rebindings (name rebindings increase risk of negative side effects, such as bugs).

Short Learning Curve

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

Write Once, Run Anywhere

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

Java Security

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

Code Clarity

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

Unicode and Internationalization

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

Hotspot and Development Efficiency

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

What You Can Expect from this tutorial

This tutorial 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 tutorial. Although Jython is a complete coding language, it is unique in its ability to complement Java development rather than appear as an alternative to Java. , "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 1 details the rules that apply to indentation, newlines, and statements. Additionally, 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. , "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. 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 , "Errors and Exceptions." 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. , "User-Defined Functions and Variable Scoping," shows how to define and use Jython functions and how to use Jython's functional coding tools. Functions are callable objects not defined within a class, but functional coding has a less succinct definition. Functional coding 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 . Jython has modules, another unit that Java does not have, and , "Modules and Packages," describes Jython's modules. Jython also has packages, as does Java, but Jython packages differ from the Java counterpart as explains. With Jython packages, modules, and classes as well as Java packages and classes, the details of the import statement quickly become important. clarifies the import statement along with modules and packages. , "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 clarifies these differences. , "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. , "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. , "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 apps 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 app. 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 apps 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 app, 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. , "GUI Development," describes how to develop graphical apps with Jython. The focus is on Java's Abstract Windowing Toolkit (AWT) and Swing app programmer's interface. Jython allows rapid development of graphical apps because of its addition of automatic bean properties and events. 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. 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. , "Database Programming," introduces the use of Jython in database programming. 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 app programmer's interface implemented with zxJDBC. discusses both of these APIs. , "Server-Side Web Programming," describes web coding 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. addresses using jythonc -compiled classes as servlets as well as an embedded Jython Servlet mapping and IBM's bean scripting framework (BSF).

Who This tutorial Is For

This tutorial 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 tutorial 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 tutorial 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 coding as well as object-oriented coding is an educational advantage.

Who This tutorial Isn't For

If you have no interest in Java, then this tutorial 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 tutorial, will not benefit from this tutorial. 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 tutorial, a poor choice for your needs. If you are already an advanced Python programmer, this tutorial may not be for you. A substantial portion of this tutorial 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.

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 tutorial, at http://www.newriders.com/, or at the Jython website, it is best to consult the mailing lists.

Comments