Python for Developers

First edition

Chapter 1


Introduction

Python is a Very High Level Language, object-oriented, dynamic and with strong typing, interpreted and interactive.

Features

Python has a clear and concise syntax, which favors the readability of source code, and makes the language more productive.

The language includes several high-level structures (lists, dictionaries, date / time, complex numbers and others) and a vast collection of modules ready for use, plus third-party frameworks that can be added. It also has features found in other modern languages, such as generators, introspection, persistence, metaclasses and unity tests. Multiparadigm, the language supports modular, functional, and object-oriented programming. Even the basic types in Python are objects. The language is interpreted through bytecode by the Python virtual machine, making the code portable. This makes it possible to build applications on one platform and run them on other systems or direct from the source.

Python is open source software (with license compatible with the General Public License (GPL), but less restrictive, allowing Python to be even incorporated into proprietary products). The language specification is maintained by the Python Software Foundation (PSF).

Besides being used as the main language in the development of systems, Python is also used as a scripting language in various pieces of software, enabling you to automate tasks and add new features, among them: LibreOffice.org, PostgreSQL, Blender, GIMP and Inkscape.

It is possible to integrate Python with other languages such as C and Fortran. In general terms, the language has many similarities with other dynamic languages such as Perl and Ruby.

History

The language was created in 1990 by Guido van Rossum, the National Research Institute for Mathematics and Computer Science in the Netherlands (CWI) and had originally focused on users as physicists and engineers. Python was designed from another existing language at the time, called ABC.

Today, the language is well accepted in the industry for high-tech companies, such as:

  • Google (Web applications).
  • Yahoo (Web applications).
  • Microsoft (IronPython: Python for. NET)
  • Nokia (available for recent lines of cell phones and PDAs).
  • Disney (3D animations).

Versions

The official implementation of Python is maintained by the PSF and written in C, and therefore is also known as CPython. The latest stable version is available for download at:

http://www.python.org/download/

For Windows platforms, simply run the installer. For other platforms, such as Linux, Python is usually already part of the system, but in some cases it may be necessary to compile and install the interpreter from the source files.

There are also implementations of Python for. NET (IronPython), JVM (Jython) and Python (PyPy).

Running programs

Example of Python program:


In [ ]:
# the character "#" indicates that the rest of the line is a comment
# A list of musical instruments
instruments = ['Bass', 'Drums', 'Guitar']

# for each name in the list of instruments
for instrument in instruments:
    # show the name of the musical instrument
    print instrument


Bass
Drums
Guitar

In the example, instruments is a list containing the items "Bass", "Drums" and "Guitar". Now instrument is a name that corresponds to each of the items on the list, as the loop is executed.

The source files are usually identified by the extension ".py" and can be run directly by the interpreter:

python apl.py

Thus apl.py will run. On Windows, the file extensions ".py", ". pyw", ". pyc" and ". pyo" are associated with Python automatically during installation, so just click a the file to run it. The ". pyw" files run with an alternate version of the interpreter that does not open the console window.

Dynamic Typing

Python uses dynamic typing, which means that the type of a variable is inferred by the interpreter at runtime (this is known as Duck Typing). By the time a variable is created by attribution the interpreter defines the type of a variable, along with the operations that can be applied.

Typing of Python is strong, ie, the interpreter checks whether the transactions are valid and does automatic coercions between incompatible types. In Python, coercions are performed automatically only between types that are clearly related, as integer and long integer. To perform the operation between non-compatible types, you must explicitly convert the type of the variable or variables before the operation.

Compilation and interpretation

The source code is translated by Python to bytecode, which is a binary format with instructions for the interpreter. The bytecode is cross platform and can be distributed and run without the original source.

By default, the parser compiles the code and stores the bytecode on disk, so the next time you run it, there is no need to recompile the program, reducing the load time of execution. If the source files are changed, the interpreter will be responsible for regenerating the bytecode automatically, even using the interactive shell. When a program or a module is invoked, the interpreter performs the analysis of the code, converts to symbols, compiles (if there is no updated bytecode on disk) and runs it in the Python virtual machine.

The bytecode is stored in files with the extension ". pyc" (normal bytecode) or ". pyo" (optimized bytecode). The bytecode can also be packaged along with an executable interpreter, to facilitate the distribution of the application, eliminating the need to install Python on each computer.

Interactive Mode

The Python interpreter can be used interactively, where lines of code are typed into a prompt (command line) shell similar to the operating system.

python

It is ready to receive commands after the appearance of the signal >>> on the screen:

Python 2.6.4 (r264:75706, Nov 3 2009, 13:20:47)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

On Windows, the interactive mode is also available via the icon "Python (command line)".

The interactive mode is a distinguishing feature of the language, as it is possible to test and modify code snippets before inclusion in programs, to extract and convert data or even analyze the state of the objects in memory, among other possibilities.

Besides the traditional interactive mode of Python, there are other programs that act as alternatives to more sophisticated interfaces (such as PyCrust):

Tools

There are many development tools for Python, such as IDEs, editors and shells (that take advantage of the interactive capabilities of Python).

Integrated Development Environments (IDEs) are software packages that integrate various development tools in an environment consistent with the goal of increasing developer productivity. Generally, IDEs include such features as syntax highlighting (colorized source code according to the syntax of the language), source browsers, integrated shell and code completion (the editor presents possible ways to complete the text it can identify while typing). Among Python IDEs, there are:

There are also text editors specialized in programming code, which have features like syntax colorization, export to other formats and convert text encoding.

These editors support multiple programming languages​​, Python among them:

Shell is the name given to interactive environments for executing commands that can be used to test small pieces of code and for activities like data crunching (extraction of information of interest in masses of data and subsequent translation to other formats).

Beyond the standard Python Shell, there are others available:

  • PyCrust
  • IPython

Packers are utilities that are used to build executables that comprise the bytecode, the interpreter and other dependencies, allowing the application to run on machines without Python installed, which facilitates program distribution.

Among packers for Python, are available:

  • py2exe (Windows only)
  • cx_Freeze (portable)

Frameworks are collections of software components (libraries, utilities and others) that have been designed to be used by other systems.

Some of the most known frameworks availble are:

  • Web: Django, TurboGears, Zope and web2py.
  • Graphic interface: wxPython, PyGTK and PyQt.
  • Scientific processing: NumPy and SciPy.
  • Image processing: PIL.
  • 2D: Matplotlib and SVGFig.
  • 3D: Visual Python, PyOpenGL and Python Ogre.
  • Object-relational mapping: SQLAlchemy e SQLObject.

Culture

The name Python was taken by Guido van Rossum from british TV program Monty Python's Flying Circus, and there are many references to the show in its documentation. For instance, Python's oficial package repository was called Cheese Shop, the name of one of the frames of the program. Currently, the repository name is Python Package Index (PYPI).

The goals of the project was summarized by Tim Peters in a text called Zen of Python, which is available in Python itself using the command:


In [6]:
import this


The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

The text emphasizes the pragmatic attitude of the Benevolent Dictator for Life (BDFL) as Guido is known in the Python community.

Proposals for improving the language are called PEPs (Python Enhancement Proposals), which also serve as a reference for new features to be implemented in the language.

In addition to the official website, other good source of information about the language are: Python Cookbook site that stores "recipes": small portions of code to accomplish specific tasks.


In [1]:



Out[1]: