Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Thursday, June 27, 2013

Using Vim to break long Python import statements

You can use ...

    :%s/^\(from.*\)\(import.*[a-z]\)\%>79v/\1\\\r\t\2/g

... to change long lines like ...

from experimental.tools.musicexpressiontools.RhythmRegionExpression import RhythmRegionExpression

... to two shorter lines like this ...

from experimental.tools.musicexpressiontools.RhythmRegionExpression \
    import RhythmRegionExpression

... in a single command.

Changing Python list comprehensions to generator comprehensions

The list comprehension ...

    assert all([x % 2 == 0 for x in sequence])

... can be rewritten as the generator comprehension ...

    assert all(x % 2 == 0 for x in sequence)

... instead.

You can use the Vim substitution :%s/all(\[\(.*\)\])/all(\1)/g to change all([...]) to all(...) everywhere in a file.

Thursday, June 6, 2013

Running Python commands in vim

Run ...

:py print 2 ** 38

... to print 274877906944 to screen in vim.

The feature works only when vim has been compiled with the the +python option enabled.

Run ...

vim --version

... to see if your install of vim was compiled with the +python option enabled.

Tuesday, January 31, 2012

Dynamically reloading Python modules

Dynamically reloading Python modules is basically risky as hell.

here're a few lines to start off intrepid investigation.

module = __import__(module_importable_name, fromlist=['*'])
os.system('touch {}'.format(module.__file__))
reload(module)
attribute = getattr(module, attribute_name)

What's the system call to touch doing there? Just something else to throw in the mix when trying to debug why Python seems not to have reloaded such and such an attribute this time around.

Seriously. Much better to avoid reloading altogether.

Saturday, July 23, 2011

Finding versions of the Abjad toolchain

Use the following commands to find versions of Abjad tools:

$ lilypond --version
GNU LilyPond 2.15.3 ...

$ python --version
Python 2.6.1

$ py.test --version
This is py.test version 2.1.0 ...

$ sphinx-build --version
Sphinx v1.0.7 ...

$ less `which easy_install`
... __requires__ = 'setuptools==0.6c9' ...

$ svn --version
svn, version 1.6.17 ...

Monday, July 18, 2011

Setting svn:ignore on __pycache__ directories

py.test 2.1 introduces the use of __pycache__ directories.

Use ...

svn propset -R svn:ignore __pycache__ directory

... to ignore ___pycache__ directories in directory and in all subdirectories of directory.

The property setting will be committed to the repository on your next check-in and will thereafter be acquired by all other users of the repository on check-out.

Updating py.test

Update py.test with easy install ...

easy_install -U pytest

... and notice the lack of period in pytest.

If you have multiple versions of Python on your system then you may need to use ...

easy_install-2.6 -U pytest

... instead.

Tuesday, October 12, 2010

Finding sphinx-build

Sphinx is an excellent tool for generating documentation for projects implemented in Python. Note that after installing Sphinx, the which command won't show you the location on the package interface directly:

which Sphinx

What you're looking for instead is the sphinx-build executable:

which sphinx-build
/usr/local/bin/sphinx-build

And it is the sphinx-build executable that you can query for help when starting and stopping the system:

which sphinx-build --help

And so on.

Monday, August 2, 2010

Using easy_install with an explicit version of Python

It is possible to have multiple versions of Pyton installed on your system:

$ ls -1 /usr/bin/py*
/usr/bin/pydoc
/usr/bin/pydoc2.5
/usr/bin/pydoc2.6
/usr/bin/python
/usr/bin/python-config
/usr/bin/python2.5
/usr/bin/python2.5-config
/usr/bin/python2.6
/usr/bin/python2.6-config
/usr/bin/pythonw
/usr/bin/pythonw2.5
/usr/bin/pythonw2.6

This can be a problem when you use easy_install to install a new Python package:

easy_install -U Sphinx

Fortunately, you will find multiple versions of easy_install on your machine:

$ ls -1 /usr/bin/easy_install*
/usr/bin/easy_install
/usr/bin/easy_install-2.5
/usr/bin/easy_install-2.6

This makes it possible to use easy_install with an explicit version of Python:

$ easy_install-2.6 -U Sphinx

Saturday, June 19, 2010

Mac OS 10.4, 10.5, 10.6 and Python install versions

Apple ships Mac OS 10.4, 10.5, 10.6 with different Python versions as follows:

10.4.x (Tiger) ==> Python 2.3.5
10.5.x (Leopard) ==> Python 2.5.1
10.6.x (Snow Leopard) ==> Python 2.6.1

Saturday, October 31, 2009

Python list copy, Python tuple copy

Full-slicing a list builds a new list:

>>> old = [1, 2, 3]
>>> new = old[:]
>>> old is new
False


But full-slicing a tuple does NOT build a new tuple:

>>> old = (1, 2, 3)
>>> new = old[:]
>>> old is new
True

Wednesday, April 15, 2009

Tracking Python function calls

It is sometimes useful to track the number of calls against a certain function in Python somewhere deep in the internals of the system. Turns out the Python global keyword can help with this.

Consider the following module:

### foo.py ###

def foo( ):
pass

### foo.py ###

Assuming that the foo module is imported at some point during execution with import foo or from foo import foo rather than being run as a script in its own right, the following use of global is possible:

### foo.py ###

visits = 0

def foo( ):
global visits
visits += 1
print 'visit number %s' % visits

### foo.py ###

Each call against foo( ) will now increment the global visits counter and print to standard out.

A not-bad use of global indeed.

Friday, June 6, 2008

Avoiding another shared reference trap in Python

Define Foo as follows.

>>> class Foo( ):
... def __init__(self, stuff = [ ]):
... self.stuff = stuff
...

Then instantiate two instances of Foo and append a number to f1 and f2.

>>> f1 = Foo( )
>>> f2 = Foo( )
>>> f1.stuff.append(17)
>>> f2.stuff.append(18)

So, what do

>>> f1.stuff

and

>>> f2.stuff

return?

Before we get to the answer, stop and consider that f1 and f2 are totally separate instances Foo. Attributes that we assign to f1 and f2 are, usually, completely independent.

>>> f1.flavor = 'cherry'
>>> f2.flavor = 'lime'
>>> f1.flavor
'cherry'
>>> f2.flavor
'lime'

And so we would hope that f1 will maintain one list of stuff while f2 will maintain another.

But, perhaps surprisingly, f1 and f2 share a single list of stuff.

>>> f1.stuff
[17, 18]
>>> f2.stuff
[17, 18]

What's going on here?

The answer has to do with order of evaluation in Python. And also with the difference between class definition time and instance instantiation time.

Immediately following our definition of Foo ...

>>> class Foo( ):
... def __init__(self, stuff = [ ]):
... self.stuff = stuff
...

... the Python interpreter defines Foo. And it is at precisely this moment of class definition that Python first evaluates and then stores default values for all class methods.

This means that stuff to an empty list and then that __init__ stores a reference to that list.

Later -- after class definition -- we instantiate first one and then another instance of Foo. At these moments of instance instantiation, Python calls Foo's initializer ... but refuses to reevaluate default arguments in __init__.

What this means is that Python evaluates default arguments once and only once at least under normal conditions. And the consequence here is that f1 and f2 wind up, frustratingly, sharing a reference to the same list of stuff.

One good solution substitutes stuff = None for stuff = [ ].

>>> class Foo( ):
... def __init__(self, stuff = None):
... if stuff is None:
... stuff = [ ]
... self.stuff = stuff

And this highlights a principle that's may not really be a best practice in Python but might as well ought to be: set function defaults to immutable types, never to mutables. Lists, of course, are mutable, which helps explain why stuff = [ ] gets us into trouble. None is immutable and works great.

For a follow-up bit of exotica, stop and ask yourself where it is, exactly, that our first, list = [ ] definition of Foo stores its reference to its single list of stuff.

Turns out the the answer is here ...

>>> Foo.__init__.im_func.func_defaults

... buried down a couple of layers, but still open for inspection.

Monday, May 12, 2008

Python tuple unpacking within a loop

Python tuple unpacking gets rid of tuple indices and temporary variables.

>>> a = range(11, 15)
>>> b = zip(range(21, 25), range(31, 35))
>>> for x, (y, z) in zip(a, b):
... print x, y, z
...
11 21 31
12 22 32
13 23 33
14 24 34

Linking Python startup.py and .pythonrc.py

On interactive startup, Python reads either $PYTHONSTARTUP or ~/pylib/startup.py, if it exists. On noninteractive startup, Python reads ~/.pythonrc.py, if it exists.

python without options counts as interactive and python -i counts as noninteractive. So

python

reads startup.py while

python -i foo.py

reads .pythonrc.py.

If it matters that the same modules preload on both interactive and noninteractive startup, ~/pylib/startup.py and ~/.pythonrc.py might help. The command is

ln ~/pylib/startup.py ~/.pythonrc.py

and it's important that ~/.pythonrc.py doesn't at first exist.

Thursday, May 8, 2008

Definitional tuple-packing in Python

Python functions may tuple-pack their arguments.

def foo(a, (b, c)):
print a, b, c

>>> foo(10, (20, 30))
10 20 30

Arguments unpack during evaluation.

More on Python Rationals

Coercing to floats internal to some other operation is inherently bad. And so Jared replaces ...

def __gt__(self, arg):
if not isinstance(arg, type(self)):
arg = self.__class__(arg)
return float(self) > float(arg)

... and friends with ...

def __gt__(self, arg):
if not isinstance(arg, type(self)):
return self.numerator > self.denominator * arg
return self.numerator * arg.denominator > arg.numerator * self.denominator

... or even ...

def __eq__(self, arg):
return self.numerator == self.denominator * arg

... which is especially nice.

Will sign trickiness ever give a wrong result? A couple dozen random cases work here and so I've put revised and reposted the implementation.

Of course what Jared's really interested in is whether the class can — or, in fact, already does — work as rational field. I'm just happy he caught that the fact that we can ditch the __cmp__ override because the presence of __gt__, __eq__, __lt__ and friends.

One question that remains is what to do with int. The current implementation goes towards zero and not towards negative infinity. So int(Rational(-6, 5)) gives -1 and not -2.

def __int__(self):
result = abs(self.numerator) // abs(self.denominator)
if self >= 0:
return result
else:
return -result

But is this right? Perhaps Google will break a tie ...

Tuesday, May 6, 2008

A good python Rational class

Python implements integers, floats, decimals and complex numbers. But no rationals. PEP 239, "Adding a Rational Type to Python", suggests ... the addition of a rational type to python. But alas. Guido said no. And that was 2001.

So developers everywhere implement their own. Duration math depends crucially on rational arithmetic and so Víctor and I are no exception. My first implementation was in 2005, I think Víctor followed soon after, and we've shared a relatively robust implementation this year. And, just this week, we've reimplemented yet again.

Some features.

The initializer requires numerator but leaves denominator optional.

>>> p = Rational(13, 8)
>>> p
13/8

>>> q = Rational(2)
>>> q
2

Unary negation, inversion and absolute value work the way you think they do.

>>> -p
-13/8

>>> ~p
8/13

>>> abs(p)
13/8

So do the inequalities.

>>> p < q, p <= q, p == q, p >= q, p > q
(True, True, False, False, False)

Integers work too.

>>> p
13/8

>>> p < 2, p <= 2, p == 2, p > 2, p >= 2
(True, True, False, False, False)

Arithmetic __add__, __sub__, __mul__, __div__ and even __truediv__ all work.

>>> p, q
(13/8, 2)

>>> p + q
29/8

>>> p - q
-3/8

>>> p * q
13/4

>>> p / q
13/16

Things that are supposed to be commutative are. Others aren't.

>>> p + q == q + p, p * q == q * p
(True, True)

>>> p - q == q - p, p / q == q / p
(False, False)

Right-operators __radd__, __rsub__, __rmul__, __rdiv__ and __rtruediv__ make integers work here too.

>>> p
13/8

>>> 2 + p
29/8

>>> 2 - p
-3/8

>>> 2 * p
13/4

>>> 2 / p
16/13

Floor division comes up every once in a while.

>>> Rational(93, 8) // 2
5

And you can compose with rational mod.

>>> Rational(93, 8) % 2
13/8

>>> Rational(93, 8) % Rational(2, 3)
7/24

>>> 93 % Rational(2, 3)
1/3

Coercion works for int and float

>>> p
13/8

>>> int(p)
1

>>> float(p)
1.625

And there're set and copy methods.

>>> p.set(15, 16)
>>> p
15/16

>>> p.copy( )
15/16
>>> id(p) == id(_)
False

The code is here. If you like -- or find bugs -- let us know.

Overriding __getslice__, __setslice__, __delslice__

Slice accessors __getslice__, __setslice__ and __delslice__ have been deprecated since python 2.0. But you'd never know it.

This becomes a problem when you decide to override any of these three functions in a custom class.

Slice accessors still show up on lists.

>>> l = range(10, 20)
>>> '__setslice__' in dir(l)
True

And help provides no deprecation warning.

Help on method-wrapper object:

__setslice__ = class method-wrapper(object)
| Methods defined here:
|
| __call__(...)
| x.__call__(...) <==> x(...)
|
| __cmp__(...)
| x.__cmp__(y) <==> cmp(x,y)
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __hash__(...)
| x.__hash__() <==> hash(x)
|
| __repr__(...)
| x.__repr__() <==> repr(x)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __objclass__
|
| __self__

So you might think that slice overrides work just like every other special method override. But no.

A naive override redefines both __setitem__ and __setslice__.


class Foo(object):

def __init__(self, *args):
self._contents = list(args)

def __setitem__(self, i, x):
self._contents[i] = x

def __setslice__(self, i, j, x):
self._contents[i : j] = x

Which appears to work.

>>> f = Foo(*range(10, 20))
>>> f._contents
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> f[3] = 130
>>> f._contents
[10, 11, 12, 130, 14, 15, 16, 17, 18, 19]

>>> f[4 : 8] = [140, 150, 160, 170]
>>> f._contents
[10, 11, 12, 130, 140, 150, 160, 170, 18, 19]

But when we add print statements ...

def __setitem__(self, i, x):
print 'Now in __setitem__'
self._contents[i] = x

def __setslice__(self, i, j, x):
print 'Now in __setslice__'
self._contents[i : j] = x

... we see otherwise.

>>> f[3] = 130
Now in __setitem__.
>>> f._contents
[10, 11, 12, 130, 14, 15, 16, 17, 18, 19]

>>> f[4 : 8] = [140, 150, 160, 170]
Now in __setitem__.
>>> f._contents
[10, 11, 12, 130, 140, 150, 160, 170, 18, 19]

The interpreter never calls __setslice__. This might lead us to the sensible conclusion that -- because the method is deprecated -- the interpreter never calls __setslice__ at all. But again no.

When our class additionally redefines __getslice__ ...

class Foo(object):

def __init__(self, *args):
self._contents = list(args)

def __getslice__(self, i, j, stride = None):
print 'Now in __getslice__.'
return self._contents[i : j : stride]

def __setitem__(self, i, x):
print 'Now in __setitem__.'
self._contents[i] = x

def __setslice__(self, i, j, x):
print 'Now in __setslice__.'
self._contents[i : j] = x

... we again find otherwise.

>>> f[4 : 8] = [140, 150, 160, 170]
Now in __setslice__.
>>> f._contents
[10, 11, 12, 13, 140, 150, 160, 170, 18, 19]

The interpreter here does call __setslice__.

So what's going on? Does the interpreter call __setslice__ or not? Is __setslice__ really deprecated or not?

To capture what's actually going on here we have to talk about dependencies between different slice-getters and -setters and item-getters and -setters and say something like "interpretation of x[i : j] passes any output of x.__getslice__ to x.__setslice__ but -- on failure -- resorts to x.__setitem__ only."

This is a mess and probably justifies deprecation in itself. But as of python 2.5 we have enough rope to hang ourselves -- the interpreter will call overridden versions of the special slice handlers ... but only sometimes.

The solution is to redefine the three item accessors __getitem__, __setitem__, __delitem__ only and to ignore the corresponding slice handlers entirely.

class Foo(object):

def __init__(self, *args):
self._contents = list(args)

def __getitem__(self, i):
print 'Now in __getitem__.'
return self._contents[i]

def __setitem__(self, i, x):
print 'Now in __setitem__.'
self._contents[i] = x

def __delitem__(self, i):
print 'Now in __delitem__.'
del(self._contents[i])

Item gets, sets and deletes work as expected.

>>> f._contents
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> f[4]
Now in __getitem__.
14

>>> f[4] = 140
Now in __setitem__.
>>> f._contents
[10, 11, 12, 13, 140, 15, 16, 17, 18, 19]

>>> del(f[4])
Now in __delitem__.
>>> f._contents
[10, 11, 12, 13, 15, 16, 17, 18, 19]

Slice gets, sets and deletes work now too.

>>> f._contents
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> f[4 : 8]
Now in __getitem__.
[14, 15, 16, 17]

>>> f[4 : 8] = [140, 150, 160, 170]
Now in __setitem__.
>>> f._contents
[10, 11, 12, 13, 140, 150, 160, 170, 18, 19]

>>> del(f[4 : 8])
Now in __delitem__.
>>> f._contents
[10, 11, 12, 13, 18, 19]

That this should be so -- that slice we get slice management for free when we override item management functions -- is something of a surprise. Stuff like f[4 : 8] is certainly slice notation. So why does the interpreter call the corresponding item handler?

The answer is that f[i], f[i : j], f['bar'] all call __getitem__ and that, in the special case of f[i : j], the interpreter passes a built-in slice instance to __getitem__.

An additional print ...

def __getitem__(self, i):
print 'Now in __getitem__.'
print 'Input is %s.' % i
return self._contents[i]

... makes the point clearer.

>>> f[4 : 8]
Now in __getitem__.
Input is slice(4, 8, None).
[14, 15, 16, 17]

The conclusion to all this is to always override the three item accessors __getitem__, __setitem__, __delitem__ and to never override the three (deprecated) slice accessors __getslice__, __setslice__, __delslice__. Why is it easy to get tripped up? Because the help pages don't exactly scream about slice management deprecation. And also because it's possible to write and successfully use f[i : j] for years without realizing that this now usually interprets as a standard call to __getitem__ with a built-in slice instance passed in.

A good coresponding disucssion of just this point (minus the explanations of why the deprecation warning goes missing) is here on pages 165 - 66 of O'Reilly's Python Cookbook.

Python superclass and subclass interface consistency

Let Bar inherit from Foo and define x against both classes explicitly. Then define Foo.y, Foo.z equal to None but derive Bar.y, Bar.z as properties.

This doesn't work.

class Foo(object):
def __init__(self, x):
self.x = x
self.y = None
self.z = None

class Bar(Foo):
def __init__(self, x):
Foo.__init__(self, x)

@property
def y(self):
return self.x * 100

@property
def z(self):
return self.x * 1000

>>> foo = Foo(7)
>>> foo.x
7
>>> foo.y
>>> foo.z

>>> bar = Bar(8)
Traceback (most recent call last):
File "", line 1, in
File "test.py", line 9, in __init__
Foo.__init__(self, x)
File "test.py", line 4, in __init__
self.y = None
AttributeError: can't set attribute

But this does.

class Foo(object):
def __init__(self, x):
self.x = x

@property
def y(self):
return None

@property
def z(self):
return None

class Bar(Foo):
def __init__(self, x):
Foo.__init__(self, x)

@property
def y(self):
return self.x * 100

@property
def z(self):
return self.x * 1000

>>> foo = Foo(7)
>>> foo.x
7
>>> foo.y
>>> foo.z

>>> bar = Bar(8)
>>> bar.x
8
>>> bar.y
800
>>> bar.z
8000

A property in the subclass must implement as a property in the superclass. The pattern here ensures the interface consistency of both.