Differences creating tuples and collections.namedtuples

John Reid j.reid at mail.cryst.bbk.ac.uk
Tue Feb 19 10:36:50 CET 2013



On 19/02/13 01:47, alex23 wrote:
> On Feb 18, 9:47 pm, John Reid <johnbaronr... at gmail.com> wrote:
>> See http://article.gmane.org/gmane.comp.python.ipython.user/10270 for more info.
> 
> One quick workaround would be to use a tuple where required and then
> coerce it back to Result when needed as such:
> 
> def sleep(secs):
>     import os, time, parallel_helper
>     start = time.time()
>     time.sleep(secs)
>     return tuple(parallel_helper.Result(os.getpid(), time.time() -
> start))
> 
> rc = parallel.Client()
> v = rc.load_balanced_view()
> async_result = v.map_async(sleep, range(3, 0, -1), ordered=False)
> for ar in async_result:
>     print parallel_helper.Result(*ar)
> 
> You can of course skip the creation of Result in sleep and only turn
> it into one in the display loop, but it all depends on additional
> requirements (and adds some clarity to what is happening, I think).
> 

Thanks all I really need is a quick work around but it is always nice to
discuss these things. Also this class decorator seems to do the job for
ipython although it does change the construction syntax a little and is
probablty overkill. No doubt the readers of this list can improve it
somewhat as well.


import logging
_logger = logging.getLogger(__name__)
from collections import namedtuple

def make_ipython_friendly(namedtuple_class):
    """A class decorator to make namedtuples more ipython friendly.
    """
    _logger.debug('Making %s ipython friendly.', namedtuple_class.__name__)

    # Preserve original new to use if needed with keyword arguments
    original_new = namedtuple_class.__new__

    def __new__(cls, *args, **kwds):
        _logger.debug('In decorator __new__, cls=%s', cls)
        if args:
            if kwds:
                raise TypeError('Cannot construct %s from an positional
and keyword arguments.', namedtuple_class.__name__)
            _logger.debug('Assuming construction from an iterable.')
            return namedtuple_class._make(*args)
        else:
            _logger.debug('Assuming construction from keyword arguments.')
            return original_new(namedtuple_class, **kwds)

    namedtuple_class.__new__ = staticmethod(__new__) # set the class'
__new__ to the new one
    del namedtuple_class.__getnewargs__ # get rid of getnewargs

    return namedtuple_class

Result = make_ipython_friendly(namedtuple('Result', 'pid duration'))




More information about the Python-list mailing list