Labels

2011/03/24

Python exec module in namespace, an importless import.

The following code demonstrates how to import a Python module into a namespace if the module file does not end with ".py" extension, contains dots or the filename is established during execution. It might be useful for unit testing of scripts of which path is known but which can't be imported directly in the testing module.

I assume that module's name is "module.filename.py.txt", the content follows.
# module.filename.py.txt
def hello():
    for i in range(3):
       print 'oO',
    print

The interactive interpreter:
Python 2.6.5 (r265:79063, Jun  3 2010, 14:39:13)
[GCC 4.1.2 20090703] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Module(object):
...     """Module object."""
...     def __init__(self, ns_dict):
...         """Populate the module."""
...         self.__dict__ = ns_dict
...
>>> mod_filename = 'module.filename.py.txt'
>>> mod_ns_alias = 'mymodule'
>>> source = open(mod_filename).read()
>>> module_code = compile(source, mod_filename, 'exec')
>>> mod_ns = {}
>>> exec module_code in mod_ns
>>> exec('%s = Module(mod_ns)' % mod_ns_alias)
>>>
>>> mymodule.hello()
oO oO oO
>>>

2011/03/20

Google Questions SOAP service

I launched a Google Questions SOAP service via on Google Appengine using a method described here. One can now fetch a list of questions frequently typed in the Google search box via the PeopleAsk.ooz.ie UI and programatically, a SOAPpy example follows:

In [1]: import SOAPpy
In [2]: client = SOAPpy.SOAPProxy('http://peopleask.ooz.ie/soap', 
                                  'http://peopleask.ooz.ie/')
In [3]: client.GetQuestionsAbout('god')
Out[3]: 
['does god exist',
 'does god love me',
 'does god hate me',
 'do god and satan talk',
 'does god love everyone',
 'does god answer prayers',
 "where is god when bad things happen"]

2011/03/19

A circular graph of Python 2.7 Types.

Generated in graphviz from Python.asdl (Python2.7)


2011/03/17

Python logging: extending standard logger by custom debug levels.

In a recent discussion I advocated for using standard loggers instead of reinventing the square wheel with a custom pretty-printer. Python's logging module is comprehensive enough and comes with 5 default loglevels (debug, info, warning, error and critical). Additionally, it allows for adding your own custom loglevels with addLevelName and invocation of logging.log(customlevel, message). It is also possible to bind custom logging methods to the logger object if the need arises. This should probably never be practiced, but is nevertheless possible, see the code snippet:
import logging

def debug_factory(logger, debug_level):
    def custom_debug(msg, *args, **kwargs):
        if logger.level >= debug_level:
           return
        logger._log(debug_level, msg, args, kwargs)
    return custom_debug    

mylogger = logging.Logger('my-logger')
ch = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s - %(funcName)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
mylogger.addHandler(ch)

for i in range(1,5):
    logging.addLevelName(logging.DEBUG+i, 'DEBUG%i' % i)
    setattr(mylogger, 'debug%i' % i, debug_factory(mylogger, logging.DEBUG+i))

def from_this_function():
    mylogger.debug('test')
    mylogger.debug1('test2')
    mylogger.debug2('test3')

def from_that_function():
    mylogger.debug('test4')
    mylogger.debug1('test5')
    mylogger.debug2('test6')
    mylogger.debug3('test7')
    
def from_another_function():
    mylogger.debug('asdasd')
    mylogger.debug1('agasdf')
    mylogger.debug2('adasdfa')
    mylogger.debug4('asdfa')
    mylogger.warning('blah')

mylogger.setLevel(logging.DEBUG)
from_this_function()    
mylogger.setLevel(logging.DEBUG+1)
from_that_function()    
mylogger.setLevel(logging.DEBUG+2)
from_another_function()