Contains utils for:

Matching first item in a list that matches some predicate. Mutex XML parser/generator that handles unknown entities. Controlling recursion depth

easymode.utils.recursion_depth(*args, **kwds)

A context manager used to guard recursion depth for some function. Multiple functions can be kept separately because it will be counted per key.

Any exceptions raise in the recursive function will reset the counter, because the stack will be unwinded.


with recursion_depth('some_function_name') as recursion_level:
    if recursion_level > getattr(settings, 'RECURSION_LIMIT', sys.getrecursionlimit() / 10):
        raise Exception("Too deep")

    # do some recursive dangerous things.
Parameters:key – The key under which the recursion depth is kept.
easymode.utils.first_match(predicate, lst)

returns the first value of predicate applied to list, which does not return None

>>> def return_if_even(x):
...     if x % 2 is 0:
...         return x
...     return None
>>> first_match(return_if_even, [1, 3, 4, 7])
>>> first_match(return_if_even, [1, 3, 5, 7])
  • predicate – a function that returns None or a value.
  • list – A list of items that can serve as input to predicate.
Return type:

whatever predicate returns instead of None. (or None).

class easymode.utils.mutex(max_wait=None, lockfile=None)

A semaphore Context Manager that uses a temporary file for locking. Only one thread or process can get a lock on the file at once.

it can be used to mark a block of code as being executed exclusively by some thread. see mutex.


from __future__ import with_statement
from easymode.utils import mutex

with mutex:
    print "hi only one thread will be executing this block of code at a time."

Mutex raises an easymode.utils.SemaphoreException when it has to wait to long to obtain a lock or when it can not determine how long it was waiting.

  • max_wait – The maximum amount of seconds the process should wait to obtain the semaphore.
  • lockfile – The path and name of the pid file used to create the semaphore.
exception easymode.utils.SemaphoreException

An exception that get thrown when an error occurs in the mutex semphore context


Loop through all bases of cls

>>> str = u'hai'
>>> for base in bases_walker(unicode):
...     isinstance(str, base)
Parameters:cls – The class in which we want to loop through the base classes.
easymode.utils.url_add_params(url, **kwargs)

Add parameters to an url

>>> url_add_params('http://example.com/', a=1, b=3)
>>> url_add_params('http://example.com/?c=8', a=1, b=3)
>>> url_add_params('http://example.com/#/irock', a=1, b=3)
>>> url_add_params('http://example.com/?id=10#/irock', a=1, b=3)


Contains classes and functions for dealing with html entities.

You need this as soon as you are doing anything with rich text fields and want to use easymode.tree.xml.decorators.toxml().


Resolve all html entities to their corresponding unicode character

class easymode.utils.xmlutils.XmlScanner(*args, **kwargs)

This class is an xml parser that will not throw errors when unknown entities are found.

It can be used as follows:

parser = sax.make_parser(["easymode.utils.xmlutils"])

All entities that can not be resolved will be skipped. This will trigger skippedEntity on the contentHandler.

A good contenthandler for this scanner is XmlPrinter because it will turn these entities into their unicode characters.

class easymode.utils.xmlutils.XmlPrinter(out=None, encoding='iso-8859-1')

XmlPrinter can be used as a contenthandler for the XmlScanner.

It will convert all skippedEntities to their unicode characters and copy these to the output stream.

You can use it as a simple xml generator, to create xml:

stream = StringIO.StringIO()
xml = XmlPrinter(stream, settings.DEFAULT_CHARSET)

def _render_page(page):
    xml.startElement('title', {})
    xml.startElement('template', {})

for child in Page.children.all():
    xml.startElement('page', {})
easymode.utils.xmlutils.create_parser(*args, **kwargs)

Because this function is defined, you can create an XmlScanner like this:

from xml import sax

parser = sax.make_parser(["easymode.utils.xmlutils"])




easymode.utils.standin.standin_for(obj, **attrs)

Returns an object that can be used as a standin for the original object.

The standin object will have extra attrs, which you can define passed as keyword arguments.

Use standin like this:

>>> a = u'I am E.T.'
>>> b = standin_for(a, origin='outerspace', package='easymode.utils.standin')
>>> b
u'I am E.T.'
>>> b == a
>>> b.origin
>>> b.package
>>> isinstance(b, unicode)
>>> type(b)
<class 'easymode.utils.standin.unicodeStandInWithOriginAndPackageAttributes'>
>>> import pickle
>>> b_pickle = pickle.dumps(b, pickle.HIGHEST_PROTOCOL)
>>> c = pickle.loads(b_pickle)
>>> b == c
>>> c
u'I am E.T.'
>>> c.origin
>>> c.package

Some types are not supported by standin_for. This is because these types are often used in statements like:

a = True
if a is True:
    print 'hi'

The is keyword checks for equal memory adress, and in case of a standin that can never be True. Also, since it is impossible to extend bool and NoneType you can never get:

isinstance(standin, bool)
isinstance(standin, NoneType)

To work with anything else but the real thing. This is why bool and NoneType instances are returned unmodified:

>>> a = False
>>> b = standin_for(a, crazy=True)
>>> b
>>> b.crazy
Traceback (most recent call last):
AttributeError: 'bool' object has no attribute 'crazy'
  • obj – An instance of some class
  • **attrs

    Attributes that will be added to the standin for obj

Return type:

A new object that can be used where the original was used. However it has extra attributes.