<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Slacy's Blog &#187; python</title>
	<atom:link href="http://slacy.com/blog/tag/python/feed/" rel="self" type="application/rss+xml" />
	<link>http://slacy.com/blog</link>
	<description>This site is solar powered!</description>
	<lastBuildDate>Tue, 07 Feb 2012 18:43:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to set session variables in Django unit tests.</title>
		<link>http://slacy.com/blog/2012/01/how-to-set-session-variables-in-django-unit-tests/</link>
		<comments>http://slacy.com/blog/2012/01/how-to-set-session-variables-in-django-unit-tests/#comments</comments>
		<pubDate>Fri, 13 Jan 2012 00:24:45 +0000</pubDate>
		<dc:creator>slacy</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://slacy.com/blog/?p=1639</guid>
		<description><![CDATA[This was super non-obvious, and I lifted code from a couple of different places. If you&#8217;ve got Django view code that gets &#38; sets session values, you&#8217;ll want to test it properly, and the standard &#8220;self.client&#8221; from Django&#8217;s TestCase doesn&#8217;t &#8230; <a href="http://slacy.com/blog/2012/01/how-to-set-session-variables-in-django-unit-tests/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This was super non-obvious, and I lifted code from a couple of different places.</p>
<p>If you&#8217;ve got Django view code that gets &amp; sets session values, you&#8217;ll want to test it properly, and the standard &#8220;self.client&#8221; from Django&#8217;s TestCase doesn&#8217;t really give you a usable session.  So, here&#8217;s the method I&#8217;m using:</p>
<pre>def stuff_session(client, dictionary):
    """Given a client (self.client in a unit test TestCase) set the session to the contents of
    the dictionary given"""
    from django.conf import settings
    from django.utils.importlib import import_module
    engine = import_module(settings.SESSION_ENGINE)
    store = engine.SessionStore()
    store.save()  # we need to make load() work, or the cookie isworthless
    client.cookies[settings.SESSION_COOKIE_NAME] = store.session_key
    session = client.session
    session.update(dictionary)
    session.save()
    # and now remember to re-login!</pre>
<p>So, in my setUp() methods, I just call stuff_session(self.client, {&#8216;key&#8217;: &#8216;value&#8217;}) and it all works out great.</p>
]]></content:encoded>
			<wfw:commentRss>http://slacy.com/blog/2012/01/how-to-set-session-variables-in-django-unit-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
	</item>
		<item>
		<title>git pull says &#8220;You are not currently on a branch&#8230;&#8221;</title>
		<link>http://slacy.com/blog/2011/04/git-pull-says-you-are-not-currently-on-a-branch/</link>
		<comments>http://slacy.com/blog/2011/04/git-pull-says-you-are-not-currently-on-a-branch/#comments</comments>
		<pubDate>Tue, 05 Apr 2011 00:21:49 +0000</pubDate>
		<dc:creator>slacy</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[pip]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://slacy.com/blog/?p=1546</guid>
		<description><![CDATA[Was working through some git error messages generated by pip installs of some Python code, and found that the issue was caused by this error: $ git pull You are not currently on a branch, so I cannot use any &#8230; <a href="http://slacy.com/blog/2011/04/git-pull-says-you-are-not-currently-on-a-branch/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Was working through some git error messages generated by pip installs of some Python code, and found that the issue was caused by this error:</p>
<pre>
$ git pull
You are not currently on a branch, so I cannot use any
'branch.&lt;branchname&gt;.merge' in your configuration file.
Please specify which remote branch you want to use on the command
line and try again (e.g. 'git pull &lt;repository&gt; &lt;refspec&gt;').
See git-pull(1) for details.
</pre>
<p>The solution (in this case, per the above directory) is to run: </p>
<pre>
$ cd /path/to/git/repository/from/above
$ git checkout master
</pre>
<p>I wish pip didn&#8217;t cause this problem.  When you specfiy a git repository on the commandline, this should happen automatically.  Maybe this has been fixed in pip 1.0 which was just released today.</p>
]]></content:encoded>
			<wfw:commentRss>http://slacy.com/blog/2011/04/git-pull-says-you-are-not-currently-on-a-branch/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
	</item>
		<item>
		<title>Breaking out of the middle of a try block in Python</title>
		<link>http://slacy.com/blog/2011/03/breaking-out-of-the-middle-of-a-try-block-in-python/</link>
		<comments>http://slacy.com/blog/2011/03/breaking-out-of-the-middle-of-a-try-block-in-python/#comments</comments>
		<pubDate>Wed, 16 Mar 2011 18:34:41 +0000</pubDate>
		<dc:creator>slacy</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[block]]></category>
		<category><![CDATA[except]]></category>
		<category><![CDATA[looping]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[try]]></category>

		<guid isPermaLink="false">http://slacy.com/blog/?p=1511</guid>
		<description><![CDATA[I had some code where I wanted to break out of a try block in Python. The code looked something like this: try: print "First" if some_condition: # What do I put here to break out of the try block? &#8230; <a href="http://slacy.com/blog/2011/03/breaking-out-of-the-middle-of-a-try-block-in-python/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I had some code where I wanted to break out of a try block in Python.  The code looked something like this:</p>
<pre>
    try:
        print "First"
        if some_condition:
            # What do I put here to break out of the try block?
        print "Second"
    except Exception as e:
        if e:
            print "Exception"
    print "Last"
</pre>
<p>(If some_condition is true, I want the output to print &#8220;First&#8221; and &#8220;Last&#8221;)</p>
<p>Neither break or continue works as expected, since &#8220;try&#8221; isn&#8217;t a loop.  I could put the body of the try block in a function, and then at the &#8220;if some_condition&#8221; section, I could just return, but that seemed messy.  I never found a clean enough solution, but one possibility is this wonky syntax:</p>
<pre>for _ in [True]:
    try:
        print "First"
        if some_condition:
            # Now, since we're in a loop, we can break out of it.
            break
        print "Second"
    except Exception as e:
        if e:
            print "Exception"
            print type(e)

print "Last"</pre>
<p>But, it&#8217;s kind of ugly, and not clear what&#8217;s going on, so I decided not to do it that way.   </p>
<p>I&#8217;m really surprised that there isn&#8217;t a standard syntax for this.  Something like &#8220;raise&#8221; but that isn&#8217;t an exception.  I guess I could raise a special value and handle it specially in th except block, but that seems messy as well. </p>
]]></content:encoded>
			<wfw:commentRss>http://slacy.com/blog/2011/03/breaking-out-of-the-middle-of-a-try-block-in-python/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
	</item>
		<item>
		<title>pymacs, ropemacs, and virtualenv, all at the same time.</title>
		<link>http://slacy.com/blog/2011/03/pymacs-ropemacs-and-virtualenv-all-at-the-same-time/</link>
		<comments>http://slacy.com/blog/2011/03/pymacs-ropemacs-and-virtualenv-all-at-the-same-time/#comments</comments>
		<pubDate>Sat, 05 Mar 2011 01:15:12 +0000</pubDate>
		<dc:creator>slacy</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[pip]]></category>
		<category><![CDATA[pymacs]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[refactoring]]></category>
		<category><![CDATA[rope]]></category>
		<category><![CDATA[ropemacs]]></category>

		<guid isPermaLink="false">http://slacy.com/blog/?p=1504</guid>
		<description><![CDATA[So, you&#8217;re developing for Python, and you want to use rope and ropemacs and pymacs, but it&#8217;s totally busted when you use your virtualenv. In addition, the packaged versions of pymacs+ropemacs for ubuntu 10.10 (and 11.04) are also kind of &#8230; <a href="http://slacy.com/blog/2011/03/pymacs-ropemacs-and-virtualenv-all-at-the-same-time/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>So, you&#8217;re developing for Python, and you want to use rope and ropemacs and pymacs, but it&#8217;s totally busted when you use your virtualenv.</p>
<p>In addition, the packaged versions of pymacs+ropemacs for ubuntu 10.10 (and 11.04) are also kind of busted, because they complains with really odd errors.</p>
<p>Here&#8217;s the solution:</p>
<p>Install the latest, greatest versions of everything into your virtualenv:</p>
<pre>. ./env/bin/activate
pip install -e hg+https://bitbucket.org/agr/rope#egg=rope
pip install -e hg+https://bitbucket.org/agr/ropemacs#egg=ropemacs
pip install -e hg+https://bitbucket.org/agr/ropemode#egg=ropemode
pip install -e git+https://github.com/pinard/Pymacs.git#egg=pymacs</pre>
<p>Unfortunately, pymacs doesn&#8217;t cleanly install, so then need to:</p>
<pre>cd env/src/pymacs
make</pre>
<p>Once that&#8217;s done, you should have env/src/pymacs/pymacs.el. Great. Now you just need to import that from your .emacs file. So, add something that looks like this to your .emacs:</p>
<pre>(setq virtual-env (getenv "VIRTUAL_ENV"))

(if (not (equal virtual-env 'nil))
      (setq load-path (append
                 (list (concat virtual-env "/src/pymacs" ))
                 load-path))
      (let ((foo 'bar))
      (require 'pymacs)
      (pymacs-load "ropemacs" "rope-")
      (setq ropemacs-enable-autoimport 't)
      ))</pre>
<p>Activate your virtualenv, and run emacs from inside there, and you should be good to go.</p>
]]></content:encoded>
			<wfw:commentRss>http://slacy.com/blog/2011/03/pymacs-ropemacs-and-virtualenv-all-at-the-same-time/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
	</item>
		<item>
		<title>An extremely simple config pattern for Python</title>
		<link>http://slacy.com/blog/2011/03/an-extremely-simple-config-pattern-for-python/</link>
		<comments>http://slacy.com/blog/2011/03/an-extremely-simple-config-pattern-for-python/#comments</comments>
		<pubDate>Thu, 03 Mar 2011 18:44:11 +0000</pubDate>
		<dc:creator>slacy</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[configs]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[python config]]></category>
		<category><![CDATA[simple config]]></category>
		<category><![CDATA[web framework]]></category>

		<guid isPermaLink="false">http://slacy.com/blog/?p=1502</guid>
		<description><![CDATA[So, you&#8217;re developing a Python application. And, you have needs for &#8220;production&#8221; versus &#8220;development&#8221; configs. If you&#8217;re using a web framework, you might have some support for doing this, but what about your other modules that you&#8217;d like to configure &#8230; <a href="http://slacy.com/blog/2011/03/an-extremely-simple-config-pattern-for-python/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>So, you&#8217;re developing a Python application.<br />
And, you have needs for &#8220;production&#8221; versus &#8220;development&#8221; configs.</p>
<p>If you&#8217;re using a web framework, you might have some support for doing this, but what about your other modules that you&#8217;d like to configure in a similar way?</p>
<p>What you sort of want to be able to say, anywhere, is something like this:</p>
<pre>import config

if config.MODULE['parameter'] == 'value':
    # do something
else:
    # do something else</pre>
<p>And, you want &#8220;import config&#8221; to automatically decide (via some means) if it&#8217;s in production or development.</p>
<p>Great, here&#8217;s a really simple pattern for you.</p>
<p>Make a directory named &#8220;config&#8221; put it somewhere on your python import path.  (It&#8217;s okay if this is app.config or some_module.config, whatever you want.)  Make the __init__ look like this:</p>
<pre>class Config(object):
    pass

if some_condition:
    from config.production import ProductionConfig
    config = ProductionConfig
else:
    config = DevelopmentConfig</pre>
<p>You need to write some_condition yourself.  You&#8217;ll probably do something like check for existance of a file, check the hostname, look at an environment variable, whatever.</p>
<p>Then, create config/production.py and config/development.py and make them look pretty much like this:</p>
<pre>from config import Config
class DevelopmentConfig(Config):
    MODULE = { 'param': 'value' }
    OTHER_MODULE = { 'other_param': 'other_value' }
    # etc.</pre>
<p>Make sure that production and development configs both specify the same arguments.  If you have shared things you want to configure, then you can make &#8220;base.py&#8221; or &#8220;shared.py&#8221; and derive from that.</p>
<p>Happy hacking!</p>
]]></content:encoded>
			<wfw:commentRss>http://slacy.com/blog/2011/03/an-extremely-simple-config-pattern-for-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
	</item>
		<item>
		<title>Extremely simple XML to Python converter</title>
		<link>http://slacy.com/blog/2011/03/extremely-simple-xml-to-python-converter/</link>
		<comments>http://slacy.com/blog/2011/03/extremely-simple-xml-to-python-converter/#comments</comments>
		<pubDate>Wed, 02 Mar 2011 01:51:25 +0000</pubDate>
		<dc:creator>slacy</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[converter]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[xml to python]]></category>

		<guid isPermaLink="false">http://slacy.com/blog/?p=1494</guid>
		<description><![CDATA[There are a ton of different ways you can encode XML, but for the style that looks like this: &#60;xml&#62; &#60;name&#62;Bob&#60;/name&#62; ... You can use this nice little function to convert it to a native Python object.  I&#8217;m using this &#8230; <a href="http://slacy.com/blog/2011/03/extremely-simple-xml-to-python-converter/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>There are a ton of different ways you can encode XML, but for the style that looks like this:</p>
<pre>&lt;xml&gt;
&lt;name&gt;Bob&lt;/name&gt;
...</pre>
<p>You can use this nice little function to convert it to a native Python object.  I&#8217;m using this to turn the results of the LinkedIn API from XML to Python, which then gets stored as JavaScript in MongoDB.</p>
<p>Set &#8220;force_list&#8221; to a list of field names that you know are list-values and it will convert those to lists in Python.  Yeah, that could be cleaner and more automatic.  Not really that proud of this, but it does work&#8230;</p>
<pre>
import xml.dom.minidom

def typeconvert(str_data):
    try:
        int_value = int(str_data)
        return int_value
    except:
        pass
    try:
        float_value = float(str_data)
        return float_value
    except:
        pass

    if str_data.lower() == 'false':
        return False
    if str_data.lower() == 'true':
        return True
    if str_data.lower() == 'null':
        return None

    return str_data

def xml_to_py(xml_text, force_list=[], convert_types=True):

    def setval(data, key, value):
        if key in force_list:
            if key not in data:
                data[key] = []
            data[key].append(value)
        else:
            if key in data:
                logging.warn("WARN: key %s, value %s in XML seems like a list" % (key, value))
                pass
            data[key] = value

    def recurse(node):
        nodename = node.nodeName
        result = {}
        if node.nodeType == xml.dom.Node.TEXT_NODE:
            nodetext = node.data.strip(' \n')
        else:
            nodetext = ''
        for child in node.childNodes:
            if child.nodeType == xml.dom.Node.TEXT_NODE:
                nodetext += child.data.strip(' \n')
            else:
                (newtext, newdata) = recurse(child)
                if newtext and newdata:
                    raise Exception("Can't have both text and data")
                if newtext != '':  # newtext could be an integer with value 0
                    if convert_types:
                        newtext = typeconvert(newtext)

                    setval(result, child.nodeName, newtext)
                elif newdata:
                    setval(result, child.nodeName, newdata)

        return (nodetext, result)

    dom = xml.dom.minidom.parseString(xml_text)
    (_text, pydict) = recurse(dom)
    return pydict</pre>
]]></content:encoded>
			<wfw:commentRss>http://slacy.com/blog/2011/03/extremely-simple-xml-to-python-converter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
	</item>
		<item>
		<title>Sometimes Python is bat-guano insane</title>
		<link>http://slacy.com/blog/2011/02/sometimes-python-is-bat-guano-insane/</link>
		<comments>http://slacy.com/blog/2011/02/sometimes-python-is-bat-guano-insane/#comments</comments>
		<pubDate>Thu, 17 Feb 2011 19:17:32 +0000</pubDate>
		<dc:creator>slacy</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[dumps]]></category>
		<category><![CDATA[loads]]></category>
		<category><![CDATA[pickle]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://slacy.com/blog/?p=1473</guid>
		<description><![CDATA[Try this on for size: import pickle d = {'a': 1} s1 = pickle.dumps(d) s2 = unicode(s1) assert(s1 == s2) d1 = pickle.loads(s1) d2 = pickle.loads(s2) assert(d1 == d2) So, what do you think happens here? Are s1 and s2 &#8230; <a href="http://slacy.com/blog/2011/02/sometimes-python-is-bat-guano-insane/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Try this on for size:</p>
<pre>import pickle

d = {'a': 1}

s1 = pickle.dumps(d)
s2 = unicode(s1)

assert(s1 == s2)

d1 = pickle.loads(s1)
d2 = pickle.loads(s2)

assert(d1 == d2)</pre>
<p>So, what do you think happens here?  Are s1 and s2 equal?  Are d1 and d2?</p>
<p>Well, hold on to your hats.  The code doesn&#8217;t even execute through pickle.loads(s2).  It throws this crazy error:</p>
<pre>Traceback (most recent call last):
  File "/tmp/test.py", line 11, in &lt;module&gt;
    d2 = pickle.loads(s2)
  File "/usr/lib/python2.6/pickle.py", line 1374, in loads
    return Unpickler(file).load()
  File "/usr/lib/python2.6/pickle.py", line 858, in load
    dispatch[key](self)
KeyError: '\x00'</pre>
<p>So, how&#8217;s that for totally insane unpredictable behavior?</p>
]]></content:encoded>
			<wfw:commentRss>http://slacy.com/blog/2011/02/sometimes-python-is-bat-guano-insane/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
	</item>
		<item>
		<title>A dict and an object, all in one.</title>
		<link>http://slacy.com/blog/2011/02/a-dict-and-an-object-all-in-one/</link>
		<comments>http://slacy.com/blog/2011/02/a-dict-and-an-object-all-in-one/#comments</comments>
		<pubDate>Tue, 15 Feb 2011 20:38:22 +0000</pubDate>
		<dc:creator>slacy</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[dict]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://slacy.com/blog/?p=1469</guid>
		<description><![CDATA[I&#8217;ve been struggling with data modeling decisions for my MongoDB interface layer.  Should results from the DB look like a dict, or like an object?  Like both?  What are the advantages and disadvantages of each approach?  I&#8217;ve got my own &#8230; <a href="http://slacy.com/blog/2011/02/a-dict-and-an-object-all-in-one/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been struggling with data modeling decisions for my MongoDB interface layer.  Should results from the DB look like a dict, or like an object?  Like both?  What are the advantages and disadvantages of each approach?  I&#8217;ve got my own opinions on this, but thought I&#8217;d share this interesting technique, making something behave as either a dict or an object, in a very easy way:</p>
<pre>class Dicty(dict, object):
    def __init__(self):
        self.__dict__ = self

d = Dicty()
d['foo'] = bar
print d.foo
d.foo = 'baz'
print d['foo']
print d
print dir(d)</pre>
]]></content:encoded>
			<wfw:commentRss>http://slacy.com/blog/2011/02/a-dict-and-an-object-all-in-one/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
	</item>
		<item>
		<title>methodpickle: A Python library for pickling function invocations.</title>
		<link>http://slacy.com/blog/2011/02/methodpickle-a-python-library-for-pickling-function-invocations/</link>
		<comments>http://slacy.com/blog/2011/02/methodpickle-a-python-library-for-pickling-function-invocations/#comments</comments>
		<pubDate>Fri, 11 Feb 2011 23:37:02 +0000</pubDate>
		<dc:creator>slacy</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[celery]]></category>
		<category><![CDATA[mongodb]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[queue]]></category>

		<guid isPermaLink="false">http://slacy.com/blog/?p=1462</guid>
		<description><![CDATA[Have you ever wanted to say &#8220;I&#8217;d like to call this function, but later&#8221;? I&#8217;ve seen people using Celery for this purpose, and it&#8217;s very well respected, but the setup is far from easy.  It has several fairly large dependencies, &#8230; <a href="http://slacy.com/blog/2011/02/methodpickle-a-python-library-for-pickling-function-invocations/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Have you ever wanted to say &#8220;I&#8217;d like to call this function, but later&#8221;?</p>
<p>I&#8217;ve seen people using <a href="http://celeryproject.org">Celery</a> for this purpose, and it&#8217;s very well respected, but the setup is far from easy.  It has several fairly large dependencies, including RabbitMQ, or you have to use one of their &#8220;ghetto queue&#8221; solutions.  I tried the ghetto queue for MongoDB, and it furiously polled the database.  That&#8217;s not cool.</p>
<p>I was also finding that it had somewhat unpredictable behavior, and I actually wanted something more simple.  I wanted to use a flow like:</p>
<ul>
<li>Take any arbitrary function or method call, and &#8220;pickle it&#8221;</li>
<li>Stick the pickled calls into a database (mongodb in my case)</li>
<li>Pull out items from the DB and execute them.</li>
</ul>
<p>Simple polling met my needs, and writing a queue in MongoDB is actually pretty simple, since they have atomic test-and-set primitives. </p>
<p>So, the only missing component was something that let me pickle method calls, and thus, I wrote a simple library to do it.  It&#8217;s called <a href="http://github.com/slacy/methodpickle">methodpickle</a> and it&#8217;s on github.  Here&#8217;s a brief example of what it lets you do:</p>
<pre>
from methodpickle.defer import defer 

def factorial(x):
    if x == 1: return 1
    return x * factorial(x-1)

if __name__ == '__main__':
    deferred = defer(factorial, 123)
    deferred_str = pickle.dumps(deferred)

    # Now, take deferred_str, store it to a db, read it back again, whatever.
    call = pickle.loads(deferred_str)
    print call.run()
</pre>
<p>And, it even works with class methods, as long as &#8216;self&#8217; is pickle-able. Cool!</p>
]]></content:encoded>
			<wfw:commentRss>http://slacy.com/blog/2011/02/methodpickle-a-python-library-for-pickling-function-invocations/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
	</item>
		<item>
		<title>Trivial function-based and class-based Python decorators.</title>
		<link>http://slacy.com/blog/2011/02/trivial-function-based-and-class-based-python-decorators/</link>
		<comments>http://slacy.com/blog/2011/02/trivial-function-based-and-class-based-python-decorators/#comments</comments>
		<pubDate>Wed, 09 Feb 2011 22:43:01 +0000</pubDate>
		<dc:creator>slacy</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[decorator]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://slacy.com/blog/?p=1453</guid>
		<description><![CDATA[Here&#8217;s a trivial function-based decorator: def wrap(method): def call(*args, **kwargs): print "calling wrapped method" return method(*args, **kwargs) return call @wrap def some_function(arbitrary, arguments=None): print "%s %s" % (arbitrary, arguments) And here&#8217;s a trivial class-based decorator: class Wrap(object): def __init__(self, method): &#8230; <a href="http://slacy.com/blog/2011/02/trivial-function-based-and-class-based-python-decorators/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s a trivial function-based decorator:</p>
<pre>
def wrap(method):
    def call(*args, **kwargs):
        print "calling wrapped method"
        return method(*args, **kwargs)
    return call

@wrap
def some_function(arbitrary, arguments=None):
    print "%s %s" % (arbitrary, arguments)
</pre>
<p>And here&#8217;s a trivial class-based decorator:</p>
<pre>
class Wrap(object):
    def __init__(self, method):
        print "construct"
        self._method = method
    def __call__(self, *args, **kwargs):
        print "call"
        self._method(*args, **kwargs)

@Wrap
def some_function(*args, **kwargs):
    print "Inside %s %s" % (str(args), str(kwargs))
</pre>
]]></content:encoded>
			<wfw:commentRss>http://slacy.com/blog/2011/02/trivial-function-based-and-class-based-python-decorators/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
	</item>
	</channel>
</rss>

