Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 1-10 of 176 total  RSS 

Collection of a bunch of named stuff

Taken from this recipe and its comments.
   1  
   2  class bunch(dict):
   3      def __init__(self,**kw):
   4          dict.__init__(self,kw)
   5          self.__dict__.update(kw)

Usage is simple.
   1  
   2  >>> o = bunch(a='A', b='B')
   3  >>> o
   4  {'a': 'A', 'b': 'B'}
   5  >>> o.a
   6  'A'
   7  >>> o.b
   8  'B'
   9  >>> 

You can use it as both an object and dict.

Get mobile cpu speed

   1  
   2  import miso
   3  print miso.get_hal_attr(11)  # 104000 for my 6600

Variable-length argument list in Python

When you declare an argment to start with '*', it takes the argument list into an array.
   1  
   2  def foo(*args):
   3    print "Number of arguments:", len(args)
   4    print "Arguments are: ", args

Using ElementTree

ElementTree is a library that make XML processing in python
much, much easier. It will be included in Python 2.5 too.
Here's how to use it to read/extract XML
   1  
   2  from elementtree.ElementTree import parse
   3  tree = parse(filename)
   4  doc = tree.getroot()
   5  
   6  # Element type (name): 
   7  print doc.tag
   8  # Element text: 
   9  print doc.text
  10  # get the child of element type book
  11  book = doc.find('book')
  12  
  13  # element's attribute
  14  book.keys()
  15  book.items()
  16  book.get('COLOR')
  17  
  18  # first matching element's text
  19  booktext = doc.findtext('book')

Read more here and here.

The zen of python

An easter egg in python.
   1  
   2  >>> import this
   3  The Zen of Python, by Tim Peters
   4  
   5  Beautiful is better than ugly.
   6  Explicit is better than implicit.
   7  Simple is better than complex.
   8  Complex is better than complicated.
   9  Flat is better than nested.
  10  Sparse is better than dense.
  11  Readability counts.
  12  Special cases aren't special enough to break the rules.
  13  Although practicality beats purity.
  14  Errors should never pass silently.
  15  Unless explicitly silenced.
  16  In the face of ambiguity, refuse the temptation to guess.
  17  There should be one-- and preferably only one --obvious way to do it.
  18  Although that way may not be obvious at first unless you're Dutch.
  19  Now is better than never.
  20  Although never is often better than *right* now.
  21  If the implementation is hard to explain, it's a bad idea.
  22  If the implementation is easy to explain, it may be a good idea.
  23  Namespaces are one honking great idea -- let's do more of those!
  24  >>> 

A dynamic form of the class statement.

These 2 methods are equivalent.
   1  
   2  # method 1
   3  class X(object):
   4      a = 1
   5  
   6  # method 2
   7  X = type('X', (object,), dict(a=1))

Python % formating

   1  
   2  # format % 2
   3  %d     : '2'
   4  %5d    : '    2'
   5  %-5d   : '2    '
   6  %05d   : '00002'
   7  %.2e   : '2.00e+000'
   8  %.2f   : '2.00'
   9  
  10  %s     : string, applying str()
  11  %-20s  : left-adjust

Python sorting

list.sort() work in place (doesn't return anything)
If you want a version that return result, use sorted() function.
   1  
   2  >>> a = [5, 2, 3, 1, 4]
   3  >>> a.sort()    # become [1, 2, 3, 4, 5]
   4  >>> a.sort(cmp) # same as above
   5  
   6  >>> a = "This is a test string from Andrew".split()
   7  >>> a.sort(key=str.lower) # using key is simpler
   8  # ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
   9  
  10  >>> import operator 
  11  >>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
  12  >>> sorted(L, key=operator.itemgetter(1))
  13  [('d', 1), ('c', 2), ('b', 3), ('a', 4)]
  14  # itemgetter allows easy Schwartzian transform

3 equivalent ways
- key=operator.itemgetter(1)
- key=lambda x: x[1]
- cmp=lambda a,b: cmp(a[1], b[1])

Learn more at Sorting Howto.

Getting HTML from Windows clipboard

Get the code for class HtmlClipboard() by Phillip Piper here.

Usage
   1  
   2  >>> cb = HtmlClipboard()
   3  >>> cb.GetAvailableFormats()
   4  [49161, 49562, 49339, 49560, 49561, 13, 1, 49334, 49335, 49333, 49344, 49478, 49171, 16, 7]
   5  >>> cb.HasHtmlFormat()
   6  True
   7  >>> cb.GetFromClipboard()
   8  >>> cb.htmlClipboardVersion
   9  '0.9'
  10  >>> cb.GetFragment()
  11  '<p>Writing to the clipboard is <strong>easy</strong> with this code.</p>'
  12  >>> cb.GetSource()
  13  'http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474121'
  14  >>> 

You can also put a html fragment to the clipboard as well.
See more detials in the recipe.

Another simple datetime+struct_time class

I had shown how datetime can be used in python 2.2
in a previous snippet. Still, it's sometimes too big.

Here's a minimal implementation. It works like both
datetime and stuct_time (as returned by localtime() and gmtime()).
   1  
   2  import time
   3  
   4  class datetime(object):
   5      def __init__(self, *argv):
   6          self.t = time.struct_time(argv+(0,)*(9-len(argv)))    # append to length 9 
   7      def __getattr__(self, name):
   8          try:
   9              i = ['year', 'month', 'day', 'hour', 'minute', 'second', 'weekday'].index(name)
  10              return self.t[i]
  11          except:
  12              return getattr(self.t, name)
  13      def __len__(self): return len(self.t)
  14      def __getitem__(self, key): return self.t[key]
  15      def __repr__(self): return repr(self.t)
  16      def now(self=None):
  17          return datetime(*time.localtime())
  18      now = staticmethod(now)
  19      def strftime(self, fmt="%Y-%m-%d %H:%M:%S"):
  20          return time.strftime(fmt, self.t)

Here's its usage
   1  
   2  # here it works like datetime.datetime()
   3  >>> t = datetime.now()
   4  >>> t.year, t.month, t.day
   5  (2006, 3, 13)
   6  >>> t.hour, t.minute, t.second
   7  (23, 3, 28)
   8  
   9  # but also works like localtime()
  10  >>> t
  11  (2006, 3, 13, 23, 3, 28, 0, 72, -1)
  12  >>> t.tm_year, t[0]
  13  (2006, 2006)
  14  >>> mktime(t)
  15  1142265808.0
  16  
  17  # good default for strftime (= ctime)
  18  >>> t.strftime()
  19  '2006-03-13 23:03:28'

« Newer Snippets
Older Snippets »
Showing 1-10 of 176 total  RSS