Friday, October 29, 2010

Another head-scratcher

I know about keywords in Python. You can't do this:

>>> and = 3
File "<stdin>", line 1
and = 3
SyntaxError: invalid syntax

But I do like simple names for objects and functions. I acquired this habit from Stroustrup's book on the C++ language, 10 years ago, before I even knew about Python.

However, I must remember not to make the names too familiar. For example, yesterday I rashly named a script And this single line caused problems that had me scratching my head:

import matplotlib.pyplot as plt

Apparently matplotlib also uses the name new for a module (although I haven't actually located it):

Traceback (most recent call last):
File "", line 1, in
import matplotlib.pyplot as plt
File "/Library/Python/2.6/site-packages/matplotlib/", line 6, in
from matplotlib.figure import Figure, figaspect
File "/Library/Python/2.6/site-packages/matplotlib/", line 18, in
from axes import Axes, SubplotBase, subplot_class_factory
File "/Library/Python/2.6/site-packages/matplotlib/", line 2, in
import math, sys, warnings, datetime, new
File "/Users/telliott_admin/Desktop/", line 1, in
import matplotlib.pyplot as plt
AttributeError: 'module' object has no attribute 'pyplot'

[UPDATE: is not a matplotlib module, it's in the standard library, but it's deprecated. It provides a way to instantiate a new object without calling __init__. I'm not sure what situation you would want to use it for other than what it says in the docs.

There is one use of new in but I don't understand it:

_subplot_classes = {}
def subplot_class_factory(axes_class=None):
# This makes a new class that inherits from SubclassBase and the
# given axes_class (which is assumed to be a subclass of Axes).
# This is perhaps a little bit roundabout to make a new class on
# the fly like this, but it means that a new Subplot class does
# not have to be created for every type of Axes.
if axes_class is None:
axes_class = Axes

new_class = _subplot_classes.get(axes_class)
if new_class is None:
new_class = new.classobj("%sSubplot" % (axes_class.__name__),
(SubplotBase, axes_class),
{'_axes_class': axes_class})
_subplot_classes[axes_class] = new_class

return new_class

1 comment:

keith-hughitt said...

Heh, never would have thought of that. On Ubuntu, it looks like is located at: