Python Abuse


Stupid iterable tricks

Since bob posted an interesting tip on using iterables at I thought I would share a nice, compact technique I use for getting "The first value from an iterable, or a default value if the iterable is exhausted" pycode:

for value in iterable:
    value = "default"

Since in python, the looping variable "value" leaks out of the for loop, and the unconditional break causes the for loop to end immediately, if the iterable has at least one value, it will be assigned to "value". If the iterable has no items and the for loop runs to completion, the else clause will be entered.

posted at 18:19:28    #    comment []    trackback []

Opening a file when all you know is the module name



import os, sys

numargs = len(sys.argv)
if numargs == 1 or numargs > 2:
    print """Usage: %s modulename""" % sys.argv[0]

from twisted.python import reflect

obj = reflect.namedAny(sys.argv[1])

fileName = obj.__file__
if fileName[-1] == 'c':
    fileName = fileName[:-1]

os.system("open %s" % fileName)

This takes advantage of the twisted utility function 'namedAny' which takes a dotted name and returns a package, module, class, function or method. This is useful for doing things like:

./ urllib2

When you just want to take a quick look at the source of a module without tediously figuring out where it is located.

This will only work on OS X, which has the "open" command, but could be changed to use the EDITOR environment variable instead.

posted at 14:09:52    #    comment []    trackback []

Python's not private enough!

>>> def foo():
...     thisIsPrivate = [0]
...     def bump():
...         thisIsPrivate[0] += 1
...     def read():
...         return thisIsPrivate[0]
...     return bump, read
>>> bumper, reader = foo()
>>> bumper(); bumper(); bumper(); print reader()

Now, for even more abuse... It's possible to access and change the list held in the closure "thisIsPrivate". But I'm not going to tell you how!

posted at 00:39:12    #    comment []    trackback []
1 2 3 4 5 6 7
8 91011121314
Nov Jan

Nothing quite like the smell of abusive python code in the morning.

XML-Image Letterimage

© 2003, Donovan Preston