Python is an object oriented, interpreted language known from its clear syntax and consistent design. This section is not meant as an exhaustive Python reference, just as a first glance introduction you may need to create policies. If you want to know more about Python, consult the Python documentation.
Chunks of python code (variables, functions and classes) can be organized into modules. To use something from a module, you'll need to import the module with the import keyword.
Example 3-1. Sample import statement
import HttpProxy |
Modules can be grouped into a package, which in itself is a module of modules. So accessing a submodule in a package can be done Zorp.HttpProxy provided you have a package named Zorp, and it has a subpackage named HttpProxy.
Zorp classes are provided in a package named Zorp. It has several submodules, for details consult the docstrings in Python files in /usr/share/zorp/pylib/Zorp/*.py
To avoid having to use full references to variables, you can use named imports. The syntax for named imports is demonstrated in the following example.
Example 3-2. Named imports
from Zorp.HttpProxy import HttpProxy |
We usually use the second form when importing identifiers. It has the benefits that we can exactly see what parts of the imported module are used.
In python, statements are not terminated with a semicolon. Line termination ends a statement, though this can be changed by using a '\' at the end of the line.
Compound statements like if and while use indentation to mark the nested commands, like in the following example:
Example 3-3. Nested commands
if self.request_url == "http://www.balabit.hu/": return Z_ACCEPT return Z_REJECT |
All variables in Python are dynamically typed, which means that the type of a variable is determined at runtime when a value is assigned to that variable.
Variables doesn't have to be explicitly declared, though reading undefined variables result in an exception.
Functions can be defined using the def keyword.
Example 3-4. Sample function declaration
def filterURL(self, method, url, version): return Z_ACCEPT |
Calling the function above can have two formats:
filterURL(self, 'GET', 'http://www.balabit.hu/', 'http/1.1') |
filterURL(self, url='http://www.balabit.hu/', \ version='http/1.1', method='GET') |
Classes in Python are similar to classes in other languages. They contain attributes (state) and functions (methods) to manipulate the state information.
Example 3-5. A sample class in Python
class MyHttp(HttpProxy): def config(self): self.transparent_mode = TRUE |
Base classes can be specified in parentheses just after the name of the class. Instances of a class can be created by "calling" the class with constructor parameters passed as arguments. Constructor of a class is named __init__, destructor is called __del__.