Table of Contents
This page gives a short introduction into the Python programming language, tailored to first-time users of the Python-bindings of opals-modules. Most information given on Python is based on the documentation given on the official Python website.
Installing Python
While the reference implementation (a.k.a. CPython) is written in C, there exist implementations in several different languages, including Java and C#. CPython today is available in 2 production versions: as Python 3 is backwards-incompatible with Python 2, and more third-party software is compatible with the latter (opals can be used with both), installing Python 2 still seems to be advisable. Ready-to-use installers for CPython are available for download that allow for extending Python later on (for that purpose, consider the package pip). However, one may opt for pre-packaged Python distributions that already come with an extended set of features. Among these, pythonxy shall be mentioned, which bundles some of the most powerful Python modules, including
- GDAL Geospatial Data Abstraction Library
- PyOpenCV Computer vision
- PIL Python Imaging Library - image processing
- IPython An enhanced Python shell, that "feels like" the one of Matlab®
- NumPy Multidimensional arrays and basic operations
- SciPy Advanced math, signal processing, optimization, statistics, etc.
- SymPy Symbolic mathematics
- Matplotlib 2D plotting library similar to the plotting features of Matlab®
- Enthought Tool Suite including Mayavi, a powerful 2D and 3D visualization tool
- VTK 3D graphics toolkit
After installation, the Python interpreter may directly be invoked from a command prompt. However, several comprehensive integrated development environments are available, offering symbolic debuggers, code completion, project management, and more. Among them, PyScripter and Spyder shall be mentioned.
Basic language features and the Python standard library
Invoking the Python interpreter and subsequently importing the module "this", reveals a compact formulation of the philosophy behind Python:
Comments
Comments are introduced by a hash sign (#) and extend until the end of line.
Numeric types
int:signed integer, 4 bytesboolean:a subtype ofint, with the predefined constantsTrue,Falselong:integer with unlimited precisionfloat:real number, typically 8 bytescomplex:complex number consisting of 2floats
All common arithmetic operators are supported, which adhere to their common precedence:
Collections
Collections combine into a common container zero or more objects, which may themselves be collections. Note that collections in Python do not restrict the contained elements to be of a common data type.
Sequence types (relevant only)
str:String literals are immutable (i.e. constant after construction) and are to be enclosed in either single or double quotes. The escape character is the backslash (). When dealing with e.g. file paths containing backslashes, turn escaping off by preceding the string literal with an 'r' ("raw").unicode:In contrast to p str, whose character set is limited to the code page in use, p unicode strings may contain practically any character of the world's writing systems. Unicode strings are preceded with a p 'u'. Kindly note that opals modules currently do not support p unicode.list:Lists are mutable objects - that is, their size and contents may be changed after construction. Lists are constructed using square brackets, with the items separated by commas.tuple:Tuples are immutable objects and are constructed by the comma operator, with or without enclosing parentheses.
Sequence types share many common operations:
x in s:Trueif an item ofsis equal tox, elseFalsex not in s:Falseif an item ofsis equal tox, elseTrues + t: the concatenation ofsandts * n, p n * s:nshallow copies ofsconcatenateds[i]:ithitem ofs, where indexing is zero-baseds[i:j]: slice ofsfromitojs[i:j:k]: slice ofsfromitojwith stepklen(s): length ofsmin(s): smallest item ofsmax(s): largest item ofss.index(i): index of the first occurence ofiinss.count(i): total number of occurences ofiins
Strings support many functions for case conversion, searching, etc. Mutable sequence types support insertion, removal and sorting of elements via respective functions. A few examples:
Set types
Set types constitute unordered collections of distinct objects. Two set types are defined:
setmutablefrozensetimmutable
Set types may be constructed by a comma-separated list of elements within curly braces (beginning with Python 2.7) and support the set operations union, intersection, difference, symmetric_difference.
Mapping types
Mapping types map hashable objects to arbitrary values (all of Python's immutable built-in types are hashable). A single mapping type is built into Python: dict. dict may be initialized with a comma-separated list of key:value pairs within curly braces:
Dynamic typing
Python variables are typed at the moment when a value is assigned, meaning that
- a variable's type may change during its lifetime, and
- there is no other way than assignment to set a variable's type
References vs. objects
Variables declared in Python are generally only handles that refer to an object. Assigning one variable to another may not copy a value, but increase the reference count of the object that both variables subsequently point to. In CPython, this does not hold for numeric types, but e.g. for sequences.
However, comparing variables using operator == is done by-value: variables are guaranteed to compare equal if their values are identical, regardless of whether they refer to the same object.
Code blocks
Code blocks group together a number of statements that shall be executed in order. In Python, code blocks must be marked by indentation (not by e.g. parentheses). This results in compact code, but may lead to problems if tabulators and space characters are both used for indentation (e.g. if Python code is read from file): following certain rules, the Python interpreter replaces tabulators with 1 to 8 blanks. That's why a mixture of tabulators and space characters in the same file is inadvisable. Nested code blocks, as e.g. in function definitions and in the branches of conditional statements, must be initiated with a colon (:).
Flow control
Amongst others, program flow may be controlled using if, for, and while statements. If a sequence type is to be filled successively in a loop, the type must be pre-defined before the loop.
List comprehensions
List comprehensions provide a concise way to create lists. They consist of an expression followed by a for clause, then zero or more for or if clauses:
As stated above, list comprehensions may be nested, allowing for processing elements of nested lists (as returned from opals modules):
Ternary conditional operator
Like e.g. C, Python features a ternary conditional operator, which evaluates to one of its branches, depending on the result of evaluating its condition. The order in which the branches are specified in Python, however may seem surprising:
- the result, if the condition evaluates to
True, followed by the keywordif, - the condition, followed by the keyword
else, - the result, if the condition evaluates to
False
Functions
Function definitions start with the keyword def, followed by
- the function's name,
- an opening parenthesis,
- zero or more argument names, separated by commas,
- a closing parenthesis,
- a colon (
:), and - the (indented) code block to be executed.
Adjacent to the argument names, default values may be specified, separated by an equal sign (=). These may be omitted in function calls. Additionally, any function argument value may be specified by argument name. Values may be returned from functions using the keyword return.
Error handling
Error handling in Python is performed using exceptions: exceptions are (small) objects that carry information about the occurred error via their type, and their string representation (error message). Division by zero, for example, results in a ZeroDivisionError to be raised, which is one of Python's predefined exception types:
Raising an exception generally makes the interpreter abort execution and return to the prompt or the calling application. However, exceptions may be handled programmatically: when iterating over a sequence, the exception may e.g. be printed on the screen, and looping may be continued.
OPALS exposes its own exception types (see opals::Exceptions) that are derived from Python's Exception, which may thus be handled specifically.
Importing modules
Anything not built into Python must be imported in order to be accessible - this holds true for opals modules and types, but also for those of the Python standard library. The import may be conducted e.g. by using the command import. Depending on the use of this command, all, some, or no prefixes must be specified to access the imported names: whatever directly follows the command import. One or more names following import may either be specified explicitly (separated by commas), or any name defined in a module may be imported using the wildcard *. By suffixing the import -command with as, aliases may be defined.
Getting help
opals modules provide most help on data types provided in this html-help also on-line in the Python interpreter, which is shown using the Python-built-in function help. This prints e.g. a module's description, together with all its methods, again with respective descriptions. In addition to the method's meaning, a method's description informs about the number and types of arguments and the type of the return value, if any. Note that the internally used C++ - data types are given.
Data persistence
If variable values shall e.g. be preserved for the next Python session, the module cPickle comes in handy, as it allows for converting most Python types (including those exposed by opals) to/from a byte string and (re-)storing them to/from file:
- Date
- 26.02.2011
