# FP in Python

Post date: Oct 07, 2012 4:31:15 PM

Functional programming extensions for a Python shell.

For lack of a better term I'm calling this code objects. You can download the zip file at the bottom of this page. This should run on any OS with Python installed. One could argue that this is a form of functional programming not to dissimilar from a spreadsheet. This program is an offshoot of my Python based spreadsheet project. I realized that a Python shell which allowed formulas to behave like spreadsheet cells could be useful for those people who like to use Python interactively as a smart calculator. Here is an example of how it can be used:

\$ python codeobjects.py

Python Shell with code objects

>>> area = '= length * width'

Calculation of (area = length * width) had errors.

{'area': None}

>>> length = 4

Calculation of (area = length * width) had errors.

{'length': 4, 'area': None}

>>> width = 6

{'width': 6, 'area': 24}

>>> area

24

>>> width = '= a + b'

Calculation of (width = a + b) had errors.

Calculation of (area = length * width) had errors.

{'width': None, 'area': None}

>>> a = 2

Calculation of (width = a + b) had errors.

Calculation of (area = length * width) had errors.

{'a': 2, 'width': None, 'area': None}

>>> b = 10

{'width': 12, 'b': 10, 'area': 48}

>>> b = 5

{'width': 7, 'b': 5, 'area': 28}

>>> area

28

>>>

So any string assignment to a single variable will be tested to see if it begins with an equals sign. If it does then it will be converted into a CodeObject. Tarjan's algorithm is used to determine the correct calculation order. As a matter of convenience I have added print statements to display when calculations have errors and the results of variables which have been changed as a result of the new assignment. Other than the re-interpretation

of strings which start with an equals sign the interpreter should act as you would expect.

Obviously unlike a spreadsheet the names for your variables do not need to follow a cell address convention of letter for the column and number for the row. When using the interactive interpreter it does not matter too much. Of course this somewhat limits what sort of fancy operations you can do on ranges of variables and such. The simple spreadsheet program PySheet marries the shell with a grid for the best of both worlds.

I am also including a second file pyShellWithCodeObjects.py which contains a slightly modified version of the wxPython pyshell application. If you have wxPython installed you might like to use this instead of the text console. This file is included as an example and is not subject to the licensing of this distribution but rather is subject to the licensing of the wxPython project.

This was originally inspired by this ActiveState Recipe and Roberto Alsina's Blog on the subject. Without these preceding efforts I never would have attempted it.