Revision: 2221
Author: pekka.klarck
Date: Sat Aug 15 15:34:18 2009
Log: quite a lot changes again, getting ready
http://code.google.com/p/robotframework/source/detail?r=2221
Modified:
/trunk/doc/python/PythonTutorial.rst
=======================================
--- /trunk/doc/python/PythonTutorial.rst Sat Aug 15 14:00:36 2009
+++ /trunk/doc/python/PythonTutorial.rst Sat Aug 15 15:34:18 2009
@@ -1,7 +1,10 @@
.. include:: <isonum.txt>
-
-Python Tutorial for Robot Framework Test Library Developers
-===========================================================
+.. include:: ../userguide/src/roles.txt
+
+
+===============================================================
+ Python Tutorial for Robot Framework Test Library Developers
+===============================================================
| Copyright |copy| Nokia Siemens Networks 2009
| Licensed under the `Creative Commons Attribution 3.0 Unported`__ license
@@ -11,12 +14,13 @@
.. contents:: Table of Contents
:depth: 2
+
Introduction
-------------
-
-* This is self learning material for `Python language`_. The target is
- to learn enough Python to be able to start creating test
- libraries for `Robot Framework`_.
+============
+
+* This is self learning material to learn how to program using `Python
+ language`_. The target is to learn enough Python to be able to start
+ creating test libraries for `Robot Framework`_.
* Earlier programming experience is expected but not absolutely
necessary.
@@ -32,77 +36,80 @@
is people without any earlier programming knowledge.
* `Python Tutorial`_, available at http://python.org and included into
- the standard Python installation at least on Windows, is also
+ the standard Python installation at least on Windows, is also very
good. Some of the sections in this training refer to it instead of
or in addition to Dive Into Python.
+* Python coding style guidelines are specified in PEP-8_. Notice that
+ Dive Into Python book uses :code:`thisStyle` for methods instead of
+ :code:`this_style` although the latter format recommended.
+
+* Another highly recommended style guide, covering many essential
+ Python idioms and techniques in depth, is *Code Like a Pythonista:
+ Idiomatic Python* available at
+ http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
+
* The official Python website at http://python.org is a good place to
- search for more documentation and Python related information in
+ find more documentation and Python related information in
general.
* If you need information about Jython, the Java implementation of
Python, you can start from http://jython.org.
-.. _Python language: http://python.org
-.. _Robot Framework: http://robotframework.org
-.. _Think Python: http://www.greenteapress.com/thinkpython/thinkpython.html
-.. _Python Tutorial: http://docs.python.org/tut/tut.html
-
Getting started
----------------
+===============
Installation
-''''''''''''
+------------
* Most Linux distributions, OS X, and other UNIX like machines have
- Python installed automatically, but on Windows you probably need to
+ Python installed by default, but on Windows you probably need to
install it separately. Installers for different platforms can be
found from http://python.org.
-* Robot Framework does not yet support Python 3.x and also this
- tutorial is based on Python 2.x. Any 2.x version up from 2.3 is
+* Robot Framework does not yet support Python 3.x versions and also
+ this tutorial is based on Python 2.x. Any 2.x version up from 2.3 is
sufficient but the latest versions are recommended.
* It is highly recommended that you configure your system so that you
- can run Python from command line simply by typing ``python`` and pressing
- enter.
+ can run Python from command line simply by typing :cli:`python` and
pressing
+ enter.
- On Windows, and possibly on some other systems, this requires
- adding Python installation directory into PATH environment
- variable. For more information and instructions on how to do it
- see `Robot Framework user guide`_.
-
-.. _Robot Framework user guide:
http://robotframework.googlecode.com/svn/tags/robotframework-2.1/doc/userguide/RobotFrameworkUserGuide.html#setting-up-environment
+ adding Python installation directory into :var:`PATH` environment
+ variable. For example `Robot Framework User Guide`_ has
+ instructions on how to do it in its *Installation* section.
Interactive interpreter
-'''''''''''''''''''''''
-
-* Start from command line by typing ``python``. On Windows you can
- also start it from ``Start > All Programs > Python 2.x``.
-
-* Statements and expressions can be written in the console. Pressing
<Enter>
- will interpret the line and any possible results are echoed. Try for
example:
+-----------------------
+
+* Open the command prompt and type :cli:`python`. On Windows you can
+ also start the interpreter by selecting ``Start > All Programs >
+ Python 2.x``.
+
+* Statements and expressions can be written in the interpreter.
+ Pressing enter will interpret the line and possible results are
+ echoed. Try for example:
.. sourcecode:: pycon
- >>> 1+2
+ >>> 1 + 2
3
-* To exit press first ``Ctrl-Z`` and then enter on Windows and
- ``Ctrl-D`` on other systems.
+* Use :cli:`Ctrl-D` to exit on UNIX like machines and :cli:`Ctrl-Z`
+ and enter on Windows.
- With Python 2.5 and newer you can exit the interpreter also with
- command ``exit()``.
-
-* `Dive Into Python`__ has some more examples.
-
-.. __: http://diveintopython.org/installing_python/shell.html
+ command :code:`exit()`.
+
+* Dive Into Python has some more examples:
+ http://diveintopython.org/installing_python/shell.html
Python editors
-''''''''''''''
+--------------
* Most general purpose text editors (Emacs, VIM, UltraEdit, ...) and
IDEs (Eclipse, Netbeans, ...) can be used to edit Python. There are
@@ -112,30 +119,30 @@
handling indentation. Make sure your editor of choise supports them
either natively or via Python plugin or mode.
-* If you don't know any editor, you can at least get started with
+* If you do not know any editor, you can at least get started with
`IDLE`_. It is included in the standard Python installation on
Windows and can be installed also on other system.
-.. _IDLE: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/
-
Variables
----------
+=========
Basic data types
-''''''''''''''''
+----------------
* Python has strings, integers, floating point numbers, Boolean values
- (``True`` and ``False``) similarly as most other programming languages.
-
-* Strings can be enclosed into double or single quotes (they do not
- have any difference like they do for example in Perl).
-
-* Unicode strings have a special syntax like ``u"Hyv\xE4\xE4
y\xF6\t\xE4!"``
- Using Unicode with Python is not covered otherwise in this tutorial.
-
-* ``None`` is a special value meaning nothing similarly as ``null`` in
- Java.
+ (:code:`True` and :code:`False`) similarly as most other programming
+ languages.
+
+* Strings can be enclosed into double or single quotes. They do not
+ have any difference like they do for example in Perl.
+
+* Unicode strings have a special syntax like :code:`u"Hyv\xE4\xE4
+ y\xF6\t\xE4!"`. Using Unicode with Python is not covered otherwise
+ in this tutorial.
+
+* :code:`None` is a special value meaning nothing similarly as
+ :code:`null` in Java.
* Try at least these on the interpreter:
@@ -150,7 +157,7 @@
Declaring variables
-'''''''''''''''''''
+-------------------
* All different values can be assigned to variables. Valid characters
in variable identifiers are letters, underscore, and numbers,
@@ -183,13 +190,15 @@
>>> x, y = 'first', 'second'
>>> x
'first'
+ >>> y
+ 'second'
First program
--------------
-
-* Create a file ``hello.py`` with your editor of choice and write this
- content into it:
+=============
+
+* Create a file :path:`hello.py` with your editor of choice and write
+ this content into it:
.. sourcecode:: python
@@ -201,22 +210,23 @@
python hello.py
-* As a result you should get ``Hello, world!`` printed into the screen.
-
-* For more interesting examples see `Dive Into Python`__.
-
-__ http://diveintopython.org/getting_to_know_python/index.html
+* As a result you should get :code:`Hello, world!` printed into the
+ screen. With Robot Framework keywords such messages would end up
+ into the log file.
+
+* For more interesting examples see for example Dive Into Python:
+ http://diveintopython.org/getting_to_know_python/index.html
Functions
----------
+=========
Creating functions
-''''''''''''''''''
+------------------
* Creating functions in Python is super easy. This example uses the
- interpreter again, but you can also write the code into the prevous
- ``hello.py`` file.
+ interpreter again, but you can also write the code into the previous
+ :path:`hello.py` file.
.. sourcecode:: pycon
@@ -230,8 +240,8 @@
norm and highly recommended) and you close the block simply by
returning to the earlier indentation level.
-* Note also that this ``hello`` function is actually already a valid
- keyword for Robot Framework!
+* Notice also that this :code:`hello` function is actually already a
+ valid keyword for Robot Framework!
* A function with arguments is not that more complicated:
@@ -245,42 +255,14 @@
>>> hello("Robot Framework")
Hello, Robot Framework!
-* The hard part in this example is string formatting (i.e. ``"Hello,
- %s!" % name``). Python has similar string formatting as for example C.
- More information about it can be found e.g. from `Dive Into Python`__.
-
-__ http://diveintopython.org/native_data_types/formatting_strings.html
-
-
-Documenting functions
-'''''''''''''''''''''
-
-* In Python functions, as well as classes and modules, are documented with
- so called `doc strings`_:
-
- .. sourcecode:: pycon
-
- >>> def hello():
- ... """Prints 'Hello, world!' to the standard output."""
- ... print "Hello, world!"
- ...
-
-* Interestingly the documentation is available dynamically:
-
- .. sourcecode:: pycon
- >>> print hello.__doc__
- Prints 'Hello, world!' to the standard output.
-
-* Robot Framework has `libdoc.py`_ tool that can generate test library
- documentation based on these doc strings. Documenting functions that
- are used as keywords is thus very important.
-
-.. _doc strings:
http://diveintopython.org/getting_to_know_python/documenting_functions.html
-.. _libdoc.py:
http://code.google.com/p/robotframework/wiki/LibraryDocumentationTool
+* The hard part in this example is string formatting (i.e. :code:`"Hello,
+ %s!" % name`) which uses similar logic as for example C language.
+ More information about it can be found e.g. from Dive Into Python:
+ http://diveintopython.org/native_data_types/formatting_strings.html
Optional and named arguments
-''''''''''''''''''''''''''''
+----------------------------
* Functions can have default values for some or all of its arguments:
@@ -312,24 +294,29 @@
1 1 10 3
>>> test(2, c=100, d=200)
2 1 100 200
+ >>> test(b=0)
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ TypeError: test() takes at least 1 non-keyword argument (0 given)
* Robot Framework keywords can have default values but they are always
- used with positional arguments. For example if above ``hello``
+ used with positional arguments. For example if above :code:`hello`
method was used as a keyword, it could be used with zero or one
- argument, and ``test`` could be used with one to four arguments.
-
-* For more information about optional and named arguments, see `Dive Into
Python`__.
-
-__ http://diveintopython.org/power_of_introspection/optional_arguments.html
+ argument, and :code:`test` could be used with one to four arguments.
+
+* Dive Into Python has good explanation for about optional and named
arguments:
+ http://diveintopython.org/power_of_introspection/optional_arguments.html
Variable number of arguments
-''''''''''''''''''''''''''''
+----------------------------
* Function can also be created so that they take any number of
arguments. This is done by prefixing an argument after required and
- optional arguments with an asterisk like ``*args``, and it means that
- the specified argument gets all the "extra" arguments as a tuple.
+ optional arguments with an asterisk like :code:`*args`, and it means that
+ the specified argument gets all the "extra" arguments as a tuple_.
+
+.. _tuple: tuples_
.. sourcecode:: pycon
@@ -346,16 +333,15 @@
* Using variable number of arguments works also with Robot Framework
keywords.
-* `Python tutorial`__ explains everything in this and earlier section in
- detail.
-
-.. __: http://docs.python.org/tut/node6.html#SECTION006700000000000000000
+* Python tutorial explains everything in this and earlier section in
+ detail:
+ http://docs.python.org/tut/node6.html#SECTION006700000000000000000
Returning values
-''''''''''''''''
-
-* Functions can use ``return`` statement to return values that can be
+----------------
+
+* Functions can use :code`return` statement to return values that can be
assigned to variables or passed to other functions:
.. sourcecode:: pycon
@@ -374,25 +360,54 @@
to variables and then used as arguments to other keywords.
+Documenting functions
+---------------------
+
+* In Python functions, as well as classes and modules, are documented with
+ so called doc strings:
+
+ .. sourcecode:: pycon
+
+ >>> def hello():
+ ... """Prints 'Hello, world!' to the standard output."""
+ ... print "Hello, world!"
+ ...
+
+* Interestingly the documentation is available dynamically:
+
+ .. sourcecode:: pycon
+
+ >>> print hello.__doc__
+ Prints 'Hello, world!' to the standard output.
+
+* Doc strings are covered pretty well in Dive Into Python:
+
http://diveintopython.org/getting_to_know_python/documenting_functions.html
+
+* Robot Framework has `libdoc.py`_ tool that can generate test library
+ documentation based on these doc strings. Documenting functions that
+ are used as keywords is thus very important.
+
+
Container data types
---------------------
+====================
* Python has a nice set of container data types build into the
language with a really simple syntax similarly as in Perl and
Ruby. You are going to use them a lot!
-* See for example `Dive Into Python`__ for more information and examples
- than shown here.
-
-__ http://diveintopython.org/native_data_types/
+* See for example Dive Into Python for more information and examples
+ than shown here: http://diveintopython.org/native_data_types
Lists
-'''''
+-----
* A list is an ordered collection of items which you normally access
by index.
+* They also have handy methods like :code:`append`, :code:`insert` and
+ :code:`pop` to add or remove items.
+
.. sourcecode:: pycon
>>> x = ['Some', 'strings', 'here']
@@ -408,7 +423,7 @@
['Some', 'strings', 'HERE', 42]
Tuples
-''''''
+------
* A tuple is a list like structure which you cannot alter after creating
it.
@@ -424,11 +439,21 @@
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
+* Notice thay you must use a trailing comma to create a tuple with one
+ element:
+
+ .. sourcecode:: pycon
+
+ >>> empty = ()
+ >>> one = (1,)
+ >>> two = (1, 2)
+
+
Dictionaries
-''''''''''''
-
-* A dictionary is an unordered collection of key-value pairs. Called
- hashmap in some other languages.
+------------
+
+* A dictionary is an unordered collection of key-value pairs. The same
+ data structure is called hashmap in some other languages.
.. sourcecode:: pycon
@@ -444,24 +469,23 @@
Control Flow
-------------
+============
Conditional execution
-'''''''''''''''''''''
+---------------------
* Python has similar :code:`if/elif/else` structure as most other
programming languages.
-* Notice that no parantheses are needed around the expression as, for
- example, Java and C require.
+* Notice that no parantheses are needed around the expression as in
+ Java or C.
.. sourcecode:: python
def is_positive(number):
if number > 0:
return True
- else:
- return False
+ return False
def greet(name, time):
if 7 < time < 12:
@@ -475,10 +499,10 @@
Looping
-'''''''
-
-* For loop allows iterating over a sequence of items such as
- list. This is probably the loop you are going to use most often.
+-------
+
+* :code:`for` loops allow iterating over a sequence of items such as
+ a list. This is probably the loop you are going to use most often.
.. sourcecode:: python
@@ -487,14 +511,14 @@
print 'Hello %s' % name
def count_up(limit):
- for num in range(limit):
- if num == 0:
- print 'Blastoff!'
+ for num in range(1, limit+1):
+ if num == limit:
+ print 'bye!'
else:
print num
-* While loop iterates as long as given expression is true. Very handy
- in testing when waiting some event to occur.
+* :code:`while` loops iterate as long as given expression is true. Very
handy
+ when waiting some event to occur.
.. sourcecode:: python
@@ -505,11 +529,20 @@
msg = try_to_receive_message()
return msg
-* Both for and while loops have typical :code:`continue` and
- :code:`break` statements that can be used to end the current
- iteration or exit the loop altogether.
-
-* Quite often for loops can be replaced with even more concise list
+* Both :code:`for` and :code:`while` loops have typical
+ :code:`continue` and :code:`break` statements that can be used to
+ end the current iteration or exit the loop altogether.
+
+* For more examples and information see
+
+ - Python Tutorial: http://docs.python.org/tut/node6.html
+ - Dive Into Python:
http://diveintopython.org/file_handling/for_loops.html
+
+
+List comprehensions
+-------------------
+
+* Quite often :code:`for` loops can be replaced with even more concise list
comprehensions or generator expressions:
.. sourcecode:: pycon
@@ -521,36 +554,36 @@
>>> sum(num for num in positive)
47
-* For more examples and information:
-
- - http://docs.python.org/tut/node6.html
- - http://diveintopython.org/file_handling/for_loops.html
- - http://diveintopython.org/native_data_types/mapping_lists.html
+* This syntax might look a bit strange first but you will love it very
+ soon. To learn more see, for example, Dive Into Python:
+ http://diveintopython.org/native_data_types/mapping_lists.html
Modules
--------
+=======
Importing modules
-'''''''''''''''''
+-----------------
* Importing existing Python modules is as simply as saying :code:`import
modulename`.
* An alternative syntax is :code:`from modulename import something`.
-* Python has a comprehensive `standard library`_ so there is plenty of
- existing code to be imported. It is recommended to study what is
- available to avoid reinventing wheels.
+* Python has a comprehensive `standard library`_ and a `package
+ index`_ with external modules so there is plenty of existing code to
+ be imported. It is recommended to study what is available to avoid
+ reinventing wheels.
Creating modules
-''''''''''''''''
-
-* Every :path:`.py` file is effectively a Python module, so you have
- already created at least :code:`hello` module.
-
-* For example we could have following code in a file
called :path:`example.py`:
+----------------
+
+* Because every :path:`.py` file is effectively a Python module, you
+ have already created at least :code:`hello` module.
+
+* For example if we have the following code in a file called
+ :path:`example.py`:
.. sourcecode:: python
@@ -560,7 +593,7 @@
if __name__ == "__main__":
hello()
- and then be able to use it like:
+ then we can use it in the interpreter (or from other modules) like:
.. sourcecode:: pycon
@@ -570,27 +603,28 @@
* :code:`if __name__ == "__main__"` block in the previous example is
important because it allows executing the file also as a script like
- :cli:`python example.py`. Automatic :code:`__name__` attribute
- (Python has many of these as you will see if you study it more) gets
- value :code:`"__main___"` when the file is run as a script and the
- if block is thus executed only in that case.
+ :cli:`python example.py`.
+
+* The automatic :code:`__name__` attribute (Python has many of these
+ as you will see if you study it more) gets value :code:`"__main___"`
+ when the file is run as a script and the :code:`if` block is thus
+ executed only in that case.
* Bigger modules can be organized into several files inside a higher
level module as submodules. In this case the higher level module is
a directory with a special :path:`___init___.py` file.
-* For more information about modules see
http://docs.python.org/tut/node8.html
-
-.. _standard library: http://docs.python.org/lib/lib.html
+* For more information about modules see Python Tutorial:
+ http://docs.python.org/tut/node8.html
Module search path (PYTHONPATH)
-'''''''''''''''''''''''''''''''
+-------------------------------
* Python modules are not automatically searched everywhere on you
machine. Python has certain default places to search modules for
(e.g. its own library directory which is often in place like
- :path:`C:\Python26\Lib` or :path:`/usr/lib/python2.6`) and
+ :path:`C:\\Python26\\Lib` or :path:`/usr/lib/python2.6`) and
additionally it looks for them from so called :var:`PYTHONPATH`.
* :var:`PYTHONPATH` is most often controlled using an environment
@@ -604,13 +638,16 @@
can be imported.
+Advanced features
+=================
+
Classes and instances
---------------------
* Python is an object-oriented language but as we have seen you do not
need to use classes everywhere like you need to with Java. It is
totally fine to just have a module with functions if that suites
- your needs but object oriented features are often really handy.
+ your needs, but object oriented features are often really handy.
* The syntax for creating classes and then instances from them is
relatively straightforward:
@@ -635,11 +672,12 @@
takes care of passing the :code:`self` argument automatically so you
do not use it when calling the method.
-* To learn more about classes you can follow `a pretty interesting
- example from Dive Into Python
- <http://diveintopython.org/object_oriented_framework/index.html>`_
- or/and study `a detailed information from Python Tutorial
- <http://docs.python.org/tut/node11.html>`_
+* To learn more about classes you can follow a pretty interesting
+ example from Dive Into Python and/or study detailed information from
+ Python Tutorial:
+
+ - http://diveintopython.org/object_oriented_framework
+ - http://docs.python.org/tut/node11.html
Exceptions
@@ -649,22 +687,34 @@
Exceptions are classes and the normal way to raise them is
:code:`raise SomeException("Error message")`.
-* Exceptions are handled in a :code:`try/except` block which can have
- an optional :code:`finally` branch.
+* Exceptions are handled in a :code:`try/except` block:
+
+ .. sourcecode:: python
+
+ try:
+ f = open(path)
+ except IOError, err:
+ print "Opening file %s for reading failed: %s" % (path, err)
+
+* The :code:`try/except` block can have multiple :code:`except`
+ branches, an optional :code:`else` to execute if no exception
+ occurred, and :code:`finally` to execute both when an exception
+ occurred and when it did not.
* Compared to Java there are some terminology differences
(:code:`raise` vs. :code:`throw` and :code:`except`
- vs. :code:`catch`) but the biggest real difference to is that there
- are no checked exceptions. This means that you do not need to add
+ vs. :code:`catch`) but the biggest real difference is that there are
+ no checked exceptions. This means that you do not need to add
:code:`throws SomeException` to methods that may raise an exception.
-* More info: http://diveintopython.org/file_handling/index.html
+* More information can be found, for example, from Dive Into Python:
+ http://diveintopython.org/file_handling/index.html
* Exceptions are an important part of the Robot Framework Library API
because keywords use them to communicate failures to the framework.
-Regular Expressions
+Regular expressions
-------------------
* Regular expressions are really handy for processing strings which is
@@ -674,12 +724,16 @@
syntax derived from Perl's regexp syntax similarly as Java and many
other languages.
-* A good introduction is
+* Dive Into Python contains a good introduction again:
http://diveintopython.org/regular_expressions/index.html
-
-Unit Testing
-------------
+* Notice that Python strings also have many useful methods
+ (e.g. :code:`startswith`, :code:`find`, :code:`isdigit`) so regexps
+ are not needed as often as in Perl or Ruby.
+
+
+Unit testing
+============
* Unit testing is important especially when you start having more
code and unit testing your test library code can be a really good
@@ -693,17 +747,17 @@
* Dive Into Python has really good chapters about
- - `unit testing`_,
- - `test-driven development`_ (TDD), and
- - refactoring_.
-
-.. _unit testing: http://diveintopython.org/unit_testing/index.html
-.. _test-driven development:
http://diveintopython.org/unit_testing/stage_1.html
-.. _refactoring: http://diveintopython.org/refactoring/index.html
+ - `unit testing`__,
+ - `test-driven development`__ (TDD), and
+ - refactoring__.
+
+__ http://diveintopython.org/unit_testing/index.html
+__ http://diveintopython.org/unit_testing/stage_1.html
+__ http://diveintopython.org/refactoring/index.html
-Writing Test Libraries
-----------------------
+Writing test libraries
+======================
Robot Framework's test library API is really simple. It is explained
fully in the `User Guide`_ but the basic features are covered here
@@ -733,6 +787,16 @@
.. footer:: Generated by reStructuredText_. Syntax highlighting by
Pygments_.
-.. _user guide: http://code.google.com/p/robotframework/wiki/UserGuide
+.. _Python language: http://python.org
+.. _Robot Framework: http://robotframework.org
+.. _Think Python: http://www.greenteapress.com/thinkpython/thinkpython.html
+.. _Python Tutorial: http://docs.python.org/tut/tut.html
+.. _PEP-8: http://www.python.org/dev/peps/pep-0008/
+.. _Robot Framework User Guide: `User Guide`_
+.. _User Guide: http://code.google.com/p/robotframework/wiki/UserGuide
+.. _libdoc.py:
http://code.google.com/p/robotframework/wiki/LibraryDocumentationTool
+.. _IDLE: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/
+.. _standard library: http://docs.python.org/lib/lib.html
+.. _package index: http://pypi.python.org
.. _reStructuredText: http://docutils.sourceforge.net/rst.html
.. _Pygments: http://pygments.org/