Filtered by Python

Page 24

Reset

Case insensitive list remove call

April 10, 2006
13 comments Python

Often when working with lists of strings in python you might want to deal with the strings in a case insensitive manner. Today I had to fix an issue where I couldn't use somelist.remove(somestring) because the somestring variable might be in there but of a different (case)spelling.

Here was the original code:: def ss(s): return s.lower().strip() if ss(name) in names: foo(name + " was already in 'names'") names.remove(name)

The problem there is that you get an ValueError if the name variable is "peter" and the names variable is ["Peter"]. Here is my solution. Let me know what you think:


def ss(s):
   return s.lower().strip()

def ss_remove(list_, element):
   correct_element = None
   element = ss(element)
   for item in list_:
       if ss(item) == element:
           list_.remove(item)
           break

L = list('ABC')
L.remove('B')
#L.remove('c') # will fail
ss_remove(L, 'c') # will work
print L # prints ['A']

Might there be a better way?

UPDATE Check out Case insensitive list remove call (part II)

Dynamic image replacement technique

February 24, 2006
6 comments Web development, Python

I've been playing with PIL's ImageDraw to create images from text. This isn't anything new but I thought I'd combine it with some Web 2.0 technology. The page is marked up like before in valid and accessible XHTML, then a javascript kicks in to automatically replace the plain text headers with image generated ones.

The benefit of this is that the image replacement stuff happens AFTER the page has been loaded for snappier response times. The page looks better with image headlines because you're not font-limited there (see apple.com for example). And most importantly: you want images for headlines but you also want to be found on Google.

Go to the demo page to see it in action.

Truncated! Read the rest by clicking the link below.

Google and Python code

February 22, 2006
14 comments Python

After reading Matt Harrison's notes about Python at Google I noticed something which I couldn't add up.

"Python programmers at Google must follow a strict style guideline (based on PEP8 with 2 spaced indenting). When engineers are first granted commit access to their SCM system, they must pass a style test."

"based on PEP8" but rejecting such an important part as indentation really is.

From PEP 8 Style Guide for Python Code

"Use 4 spaces per indentation level."

Truncated! Read the rest by clicking the link below.

tempfile in Python standard library

February 7, 2006
7 comments Python

I learnt something useful today which I can't explain. When you use the tempfile module in the Python standard library and the mkstemp() function you get two things back: an integer and a string.:


>>> import tempfile
>>> x, y = tempfile.mkstemp()
>>> x, type(x)
(3, <type 'int'>)
>>> y, type(y)
('/tmp/tmpK19sIx', <type 'str'>)
>>> help(tempfile.mkstemp)

I don't know what to do with the integer so I just ignore it. I thought I would get the result of open("/tmp/tmpK19sIx","w+b").

Truncated! Read the rest by clicking the link below.

Size comparison of Zope3, Django and TurboGears

February 4, 2006
10 comments Python

There's been a lot of debate in the python blog community about which web framework is best for everyone else. There's also been a hot debate about templating languages much fueled by Guido's rejection of XMLish requirements. In the few blogs I've followed there seems to be a couple of finalists that deserve extra scrutiny: Zope3, Django and TurboGears.

I'm drooling over all of them. Zope3 feels like a wise granddad with vigour, Django as a bubblegum-chewing teenager with lots of energy and TurboGears as something in between. (if Twisted was to get an analogy it'd be Einstein or someone like that) I want to use all three or at least Zope3 and one of Django or TurboGears depending on the project. Stuff that needs thinking and will have to last and scale: Zope3. Quick and simple websites about a single topic: Django/TurboGears.

Truncated! Read the rest by clicking the link below.

Setting security declarations to Zope classes

February 2, 2006
5 comments Python, Zope

If you're into Zope python product stuff, read on, otherwise don't bother.

Thanks to Brian Lloyd (Zope corp) and Florent Guillaume (Nuxeo) I now know how to set security declarations on a class outside the class. It doesn't work like a normal python class (new or old style) which was a bit of a surprise. This is how you do it in a "normal" python class:


class _Z:
  def __init__(self):
      self.z = "Z"
  def declareProtected(self, *a,**k):
      print "++declare something+"

def foo():
  print "I'm being called"
  return _Z()

class A:
  security=foo()
  def __init__(self):
      pass
A.security.declareProtected("foo")

Truncated! Read the rest by clicking the link below.

Yahoo! Inbound Links API

November 27, 2005
0 comments Python

Had a quick play with Yahoo!'s Inbound Links API today. You use their web services API to check which other URLs a URL is linked to from. This can come in handy if you want to know which other sites make a link to your article. Googleblog is using this (obviously not by using the Yahoo! API); look at this blog post for example and scroll to the end of the text.

The inspiration came from Fredrik Lundh's term extraction example that I'm actually now use in a production site. So I basically took Fredriks code and modified it for Inbound Links.

Truncated! Read the rest by clicking the link below.

Filename splitter

November 15, 2005
4 comments Python, Zope

I need to create a Zope index for a ZCatalog that is KeywordIndex. A KeywordIndex is a list (array if you like) that is used to describe some data. For example, if the data is "Peter is a Swedish Londoner", the the keywords are ("peter", "swedish", "londoner"). What about if the data you want to create an index of is a filename like "NameLog.txt" or "holiday-00412-juli-05.jpg". I've now quickly written a little something that seems to do a decent job. It splits the filenames (these are filenames only and no paths) by caMel structure, dot (.), underscore (_), dash (-) and digits.

If you want to play with my little script, have a look at filenamesplitter.py If you open that script you'll see that it tests a whole bunch of filenames (taken from the Demo issuetracker) and if you want to see what this the result is, here it is:

Truncated! Read the rest by clicking the link below.

"Clever" date formatting accessibility

November 10, 2005
14 comments Python, Zope

Last night I wrote a little function that tries to show dates cleverly by comparing the date with todays date, it formats the date differently.

If the date is today is just says "Today 10:00" and for yesterday it says "Yesterday 10:00". If it's within a week it shows is like this "Thursday 10:00". If the date is older than about 30 days it skips the time part and just shows "13-May 2005" and if anything else (ie. > 7 and < 30 days) it shows the whole thing like this "13-Oct 2005 10:00".

What do you think about this? ...from a usability/accessability point of view. One counter argument I have against this is that if you print off a page where it says "Today 12:22" and leave that printed paper for a few days, what "Today" means will change.

To demonstrate it, I've put together a little demo page so that you can get a feel for how it works. Please let me know what you think.

Whitelist blacklist logic

November 2, 2005
7 comments Python

Tonight I need a little function that let me define a list of whitelisted email address and a list of blacklisted email address. This is then "merged" in a function called acceptOriginatorEmail(emailaddress) which is used to see if a particular email address is acceptable.

I've never written something like this before so I had to reinvent the wheel and guess my way towards a solution. My assumptions are that you start with whitelist and return True on a match on the blacklist, then you check against the blacklist and return False on a match and default to True if no match is made.

This makes it possible to define which email addresses should be accepted and which ones should be rejected like this:


whitelist = ('*@peterbe.com', 'bill.gates@microsoft.com')
blacklist = ('*@microsoft.com')

Truncated! Read the rest by clicking the link below.