analitics

Pages

Sunday, October 14, 2012

About new release - Python 3.3.0

The new Python 3.3.0 was released on September 29th, 2012.

It's been two weeks since it was launched last version of python and I don't have found complaints about this release.

We can read more about updates and changes made by developers here.

What I think it's more significantly to this version:

  • The new "faulthandler" module that helps diagnosing crashes
  • The new "unittest.mock" module
  • The new "ipaddress" module
  • The "sys.implementation" attribute
  • A policy framework for the email package, with a provisional (see PEP 411) policy that adds much improved unicode support for email header parsing
  • A "collections.ChainMap" class for linking mappings to a single unit
  • Wrappers for many more POSIX functions in the "os" and "signal" modules, as well as other useful functions such as "sendfile()"
  • Hash randomization, introduced in earlier bugfix releases, is now switched on by default
  • A C implementation of the "decimal" module, with up to 120x speedup for decimal-heavy applications
  • The import system (__import__) is based on importlib by default
  • The new "lzma" module with LZMA/XZ support
  • PEP 397, a Python launcher for Windows
  • PEP 405, virtual environment support in core

Let's see how to working the new Python 3.3.0

First download it , unzip and install it. See next:

/Python-3.3.0 $ ./configure 
checking build system type... i686-pc-linux-gnu
checking host system type... i686-pc-linux-gnu
checking for --enable-universalsdk... no
checking for --with-universal-archs... 32-bit
checking MACHDEP... linux
checking for --without-gcc... 

The next step is ...

$ make all

And finally ...

# su 
# ./python setup.py build
running build
running build_ext
INFO: Can't locate Tcl/Tk libs and/or headers

Python build finished, but the necessary bits to build these modules were not found:
_bz2               _dbm               _gdbm           
_lzma              _sqlite3           _ssl            
_tkinter           readline                           
To find the necessary bits, look in setup.py in detect_modules() for the module's name.

I will use it without this modules, until I find a way to fix it.

$ ./python 
Python 3.3.0 (default, Oct 14 2012, 21:42:00) 
[GCC 4.4.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import ipaddress

Tuesday, October 2, 2012

Tuples can put you in difficulty.

They are two examples of sequence data types in python.

Today I will tell about tuples.

A tuple consists of a number of values separated by commas.

The biggest problem is when we do not know the number of these values ​​or type.

Let me illustrate with a function that returns a tuple.

This is a known tuple but we will use like an unknown tuple.

Let's see the python code and some errors:

>>> import sys
>>> if hasattr(sys, 'version_info'):
...     print sys.version_info()
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: 'tuple' object is not callable

Is very correct to got this error.

And the result using the print function:

>>> if hasattr(sys, 'version_info'):
...     print "%s" % str(sys.version_info)
... 
(2, 6, 4, 'final', 0) 

>>> if hasattr(sys, 'version_info'):
...     sys.stderr.write("%s" % str(sys.version_info))
... 
(2, 6, 4, 'final', 0)>>> 

or if you can use the repr function.


>>> if hasattr(sys, 'version_info'):
...     sys.stderr.write("%s" % repr(sys.version_info))
... 
(2, 6, 4, 'final', 0)>>> 

The official Python documentation says __repr__ is used to compute the “official” string representation of an object and __str__ is used to compute the “informal” string representation of an object.

In my opinion , the correct way it's to use repr. For example:

>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2012-10-02 22:45:57.634977'
>>> repr(today)
'datetime.datetime(2012, 10, 2, 22, 45, 57, 634977)'

As we see all values from tuples it's show.

Sunday, September 23, 2012

Setting up Vim to work with Python - part 2

You can customize Vim for editing a specific file.

In this case is our python script files.

To do that you can use modelines, or auto commands, or filetype plugins.

For example , if you want to see the number on rows then just set the boolean number option to true.

set number

The keys PageUp and PageDown are mapped to Ctr+U and Ctr+D.

The next changes of the vimrc file will move cursor only by half of screen.


map <PageUp> <C-U>
map <PageDown> <C-D>
imap <PageUp> <C-O><C-U>
imap <PageDown> <C-O><C-D>

To move the cursor to the end of the screen they have to be triggered twice:

map <PageUp> <C-U><C-U>
map <PageDown> <C-D><C-D>
imap <PageUp> <C-O><C-U><C-O><C-U>
imap <PageDown> <C-O><C-D><C-O><C-D>

Then you can add next line to prevent the cursor from changing the current column when jumping to other lines within the window.

set nostartofline

To add some lines on your python file.

For example many python files start with this:

#!/usr/bin/env python 
#-*- coding: utf-8 -*-

Just add the next line in your vimrc file.

:iabbrev newpy  #!/usr/bin/env python <cr>#-*- coding: utf-8 -*-

On your first line from your python file in the insert mode , write newpy and press Enter key.

Also will be a good idea to take a look at the official .vimrc for following PEP 7 & 8 conventions.

...and the result of this changes.


Saturday, September 22, 2012

Setting up Vim to work with Python - part 1

You need to use mercurial.

Mercurial is a free, distributed source control management tool.

It is mainly implemented using the Python programming language and C.

To use it , just see the next command.

# hg clone https://vim.googlecode.com/hg/ vim 
requesting all changes
adding changesets
adding manifests
adding file changes
added 3831 changesets with 24526 changes to 2566 files (+2 heads)
updating working directory
2385 files updated, 0 files merged, 0 files removed, 0 files unresolved

Go to vim folder.

# cd vim/src/

Use configure to builds a Makefile file.

src # ./configure --enable-pythoninterp --with-features=huge --prefix=$HOME/opt/vim
configure: creating cache auto/config.cache
checking whether make sets $(MAKE)... yes
checking for gcc... gcc
checking whether the C compiler works... yes
...

The next commands make builds the program and make install to install the program.

src # make && make install
mkdir objects
...

Now let's try to make working well.

src # mkdir -p $HOME/bin
src # cd $HOME/bin
bin # ls
vim
bin # ln -s $HOME/opt/vim/bin/vim
bin # ls
vim
bin # which vim
/usr/bin/vim
bin # vim --version 
VIM - Vi IMproved 7.2 (2008 Aug 9, compiled Sep 21 2009 11:22:49)
Included patches: 1-245

If you read all the output , will see something like this:

+profile +python +quickfix 

The main goal is to use vimrc.

For example you cand do this.

" Wrapping and tabs spaces.
set tw=78 ts=4 sw=4 sta et sts=4 ai

" Update syntax highlighting.
let python_highlight_all = 1

" Create smart indenting
set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class

" Auto completion using ctrl-space
set omnifunc=pythoncomplete#Complete
inoremap <nul> <C-x><C-o>

With just few lines can change and improve your work.

Tuesday, September 18, 2012

How to compile your python script .

There're situations when we want to compile the python script.

In this case , we have a python script named your_script.py.

The next script code will make one new your_script.pyc file.

import py_compile
py_compile.compile('your_script.py')

Note: this will hide the python code, but some strings can be view.

For example , if you use this in your_script.py.

print 'This is a string'

The string This is a string can be show in pyc file.

Thursday, September 13, 2012

Simple python script - Voronoi diagram

Today I show you how to make Voronoi diagram using python.

I use this to make textures for underwater.

This is just one example. But you can improve to control all cells of voronoi diagram.

The theory say:

In mathematics, a Voronoi diagram is a special kind of decomposition of a metric space, determined by distances to a specified family of objects (subsets) in the space. These objects are usually called the sites or the generators...Source : wikipedia.

I used the euclidean distance to make the Voronoi diagram because it's the most familiar case.

About wikipedia - Euclidean_distance: In mathematics, the Euclidean distance or Euclidean metric is the "ordinary" distance between two points that one would measure with a ruler, and is given by the Pythagorean formula...

My python script use the next python modules:

PIL - this allow me to use image functions.

random - this module give me... random numbers.

math - some math functions.

Let's see the source code :


from PIL import Image
import random
import math

Now I make the function named gen_voronoi.

This take the height and width of the output image and the number of cells.

The function has some random variables for red , green , blue - nr,ng,nb.

The function hypot is not accessible directly so we need to import math module and using math static object.

The return value is the Euclidean norm : sqrt(x*x + y*y).


def gen_voronoi(w, h, cells):
 image = Image.new("RGB", (w, h))
 putpixel = image.putpixel
 img_x, img_y = image.size
 nx = []
 ny = []
 nr = []
 ng = []
 nb = []
 for i in range(cells):
  nx.append(random.randrange(img_x))
  ny.append(random.randrange(img_y))
  nr.append(random.randrange(256))
  ng.append(random.randrange(256))
  nb.append(random.randrange(256))
 for y in range(img_y):
  for x in range(img_x):
   dmin = math.hypot(img_x-1, img_y-1)
   j = -1
   for i in range(cells):
    d = math.hypot(nx[i]-x, ny[i]-y)
    if d < dmin:
     dmin = d
     j = i
   putpixel((x, y), (nr[j], ng[j], nb[j]))
 image.save("output.png", "PNG")
 image.show()

Use the function to make the output.png image.


gen_voronoi(200, 200, 55)

The result is :