Posts Tagged ‘Python’

RPy – simple and efficient access to R from Python

July 28, 2009

RPy is an interface that allows you to call R functions and handle R objects in Python.

R language

Advertisements

Using mutable objects as default parameter in Python

July 22, 2009

We just came across a weird Python behaviour (of course only weird if you don’t know why). If you use mutable objects such as lists as the default parameter in a function declaration, you might end up with some unintented behaviour. Everytime the function modifies the object, the default value is in effect modified as well (e.g. appending to the list). This is also explained in the Python documentation:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, …

Find the whole thing here.

Statistics with Python

April 11, 2008

Python for scientific use. Part I: Data Visualization

Python for scientific use, Part II: Data analysis

Check if an entry is a file or directory in Python

December 3, 2007

To check whether an entry is a file or a directory in python, use the os.path.isdir() method. To read some file attributes, use the os.stat() method. The following code will read all entries in the current directory and then print out whether the entry is a file or a directory together with the time the file/dir was created.


import os, time
dirList = os.listdir("./")
for d in dirList:
    if os.path.isdir(d) == True:
        stat = os.stat(d)
        created = os.stat(d).st_mtime
        asciiTime = time.asctime( time.gmtime( created ) )
        print d, "is a dir  (created", asciiTime, ")"
    else:
        stat = os.stat(d)
        created = os.stat(d).st_mtime
        asciiTime = time.asctime( time.gmtime( created ) )
        print d, "is a file (created", asciiTime, ")"