Python Abuse 2003/11

2003-11-25

Stupid iterable tricks

Since bob posted an interesting tip on using iterables at http://www.pycs.net/bob/weblog/2003/11/24.html#P14 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:
    break
else:
    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 []
 
2003-11-18

Opening a file when all you know is the module name

pycode:

#!/usr/bin/python

import os, sys

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

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:

./openit.py 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 []
 
2003-11-08

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()
3

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 []
November
MoTuWeThFrSaSu
      1 2
3 4 5 6 7 8 9
10111213141516
17181920212223
24252627282930
Oct Dec

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

XML-Image Letterimage

© 2003, Donovan Preston