HomePython softwarell.misc

ll.misc

Miscellaneous utility functions and classes

ll.misc contains various utility functions and classes used by the other LivingLogic modules and packages.

def item​(iterable, index, default=None):

Returns the index'th item from the iterable. index may be negative to count from the end. E.g. 0 returns the first item produced by the iterator, 1 the second, -1 the last one etc. If index is negative the iterator will be completely exhausted, if it's positive it will be exhausted up to the index'th item. If the iterator doesn't produce that many items default will be returned.

index may also be an iterable of indexes, in which case item will be applied recursively, i.e. item(["foo", "bar"], (1, -1)) returns 'r'.

def first​(iterable, default=None):

Return the first item from the iterable. If the iterator doesn't produce any items default will be returned.

def last​(iterable, default=None):

Return the last item from the iterable. If the iterator doesn't produce any items default will be returned.

def count​(iterable):

Count the number of items produced by the iterable. Calling this function will exhaust the iterator.

def notimplemented​(function):

A decorator that raises NotImplementedError when the method is called. This saves you the trouble of formatting the error message yourself for each implementation.

def withdoc​(doc):

A decorator that adds a docstring to the function it decorates. This can be useful if the docstring is not static, and adding it afterwards is not possible.

class _propclass_Meta​(type):

def __new__​(cls, name, bases, dict):

class propclass​(property):

propclass provides an alternate way to define properties.

Subclassing propclass and defining methods __get__, __set__ and __delete__ will automatically generate the appropriate property:

class name(misc.propclass):
   """
   The name property
   """
   def __get__(self):
      return self._name
   def __set__(self, name):
      self._name = name.lower()
   def __delete__(self):
      self._name = None

def format_class​(obj):

Format the name of the class of obj:obj:

>>> misc.format_class(42)
'int'
>>> misc.format_class(open('README.rst', 'rb'))
'_io.BufferedReader'

def format_exception​(exc):

Format an exception object:

>>> misc.format_exception(ValueError("bad value"))
'ValueError: bad value'

def exception_chain​(exc):

Traverses the chain of exceptions. This is a generator.

class Pool​(object):

A Pool object can be used as an inheritable alternative to modules. The attributes of a module can be put into a pool and each pool can have base pools where lookup continues if an attribute can't be found.

def __init__​(self, *objects):

def register​(self, object):

Register object in the pool. object can be a module, a dictionary or a Pool objects (with registers the pool as a base pool). If object is a module and has an attribute __bases__ (being a sequence of other modules) this attribute will be used to initialize selfs base pool.

def __getitem__​(self, key):

def __getattr__​(self, key):

def clear​(self):

Make self empty.

def clone​(self):

Return a copy of self.

def __repr__​(self):

def iterone​(item):

Return an iterator that will produce one item: item.

class Iterator​(object):

Iterator adds __getitem__ support to an iterator. This is done by calling item internally.

def __init__​(self, iterator):

def __getitem__​(self, index):

def __iter__​(self):

def __next__​(self):

def __bool__​(self):

def get​(self, index, default=None):

Return the index'th item from the iterator (or default if there's no such item).

class Queue​(object):

Queue provides FIFO queues: The method write writes to the queue and the method read read from the other end of the queue and remove the characters read.

def __init__​(self):

def write​(self, chars):

Write the string chars to the buffer.

def read​(self, size=-1):

Read up to size character from the buffer (or all if size is negative). Those characters will be removed from the buffer.

class Const​(object):

This class can be used for singleton constants.

def __init__​(self, name, module=None):

def __repr__​(self):

class FlagAction​(argparse.Action):

FlagAction can be use with argparse for options that represent flags. An options can have a value like yes or no for the correspending boolean value, or if the value is omitted it is the inverted default value (i.e. specifying the option toggles it).

def __init__​(self, option_strings, dest, default=False, help=None):

def _get_kwargs​(self):

def str2bool​(self, value):

def __call__​(self, parser, namespace, values, option_string=None):

def tokenizepi​(string):

Tokenize the string object string according to the processing instructions in the string. tokenize will generate tuples with the first item being the processing instruction target and the second being the PI data. "Text" content (i.e. anything other than PIs) will be returned as (None, data).

def itersplitat​(string, positions):

Split string at the positions specified in positions.

For example:

>>> from ll import misc
>>> import datetime
>>> datetime.datetime(*map(int, misc.itersplitat("20090609172345", (4, 6, 8, 10, 12))))
datetime.datetime(2009, 6, 9, 17, 23, 45)

This is a generator.

def module​(source, filename='unnamed.py', name=None):

Create a module from the Python source code source. filename will be used as the filename for the module and name as the module name (defaulting to the filename part of filename).

def javaexpr​(obj):

Return a Java expression for the object obj.

class SysInfo​(object):

A SysInfo object contains information about the host, user, python version and script. Available attributes are host_name, host_fqdn, host_ip, host_sysname, host_nodename, host_release, host_version, host_machine, user_name, user_uid, user_gid, user_gecos, user_dir, user_shell, python_executable, python_version, pid, script_name, short_script_name and script_url.

SysInfo object also support a mimimal dictionary interface (i.e. __getitem__ and __iter__).

One module global instance named sysinfo is created at module import time.

def __init__​(self):

property host_name:

def __get__​(self):

property host_fqdn:

def __get__​(self):

property host_ip:

def __get__​(self):

def _make_host_info​(self):

property host_sysname:

def __get__​(self):

property host_nodename:

def __get__​(self):

property host_release:

def __get__​(self):

property host_version:

def __get__​(self):

property host_machine:

def __get__​(self):

def _make_user_info​(self):

property user_name:

def __get__​(self):

property user_uid:

def __get__​(self):

property user_gid:

def __get__​(self):

property user_gecos:

def __get__​(self):

property user_dir:

def __get__​(self):

property user_shell:

def __get__​(self):

property python_executable:

def __get__​(self):

property python_version:

def __get__​(self):

property pid:

def __get__​(self):

property script_name:

def __get__​(self):

property short_script_name:

def __get__​(self):

property script_url:

def __get__​(self):

def __getitem__​(self, key):

def __iter__​(self):

class monthdelta​(object):

monthdelta objects can be used to add months/years to a datetime.datetime or datetime.date object. If the resulting day falls out of the range of valid days for the target month, the last day for the target month will be used instead:

>>> import datetime
>>> from ll import misc
>>> datetime.date(2000, 1, 31) + misc.monthdelta(1)
datetime.date(2000, 2, 29)

def __init__​(self, months=0):

def __bool__​(self):

def __hash__​(self):

def __eq__​(self, other):

def __ne__​(self, other):

def __lt__​(self, other):

def __le__​(self, other):

def __gt__​(self, other):

def __ge__​(self, other):

def __add__​(self, other):

def __radd__​(self, other):

def __sub__​(self, other):

def __rsub__​(self, other):

def __neg__​(self):

def __abs__​(self):

def __mul__​(self, other):

def __rmul__​(self, other):

def __floordiv__​(self, other):

def __truediv__​(self, other):

def __str__​(self):

def __repr__​(self):

def months​(self):

class Timeout​(Exception):

Exception that is raised when a timeout in timeout occurs.

def __init__​(self, seconds):

def __str__​(self):

def timeout​(*args, **kwds):

A context manager that limits the runtime of the wrapped code.

This doesn't work with threads and only on UNIX.

def notifystart​():

Notify OS X of the start of a process by removing the previous notification.

def notifyfinish​(title, subtitle, message):

Notify OS X of the end of a process.

def prettycsv​(rows, padding=' '):

Format table rows.

rows must be a list of lists of strings (e.g. as produced by the csv module). padding is the padding between columns.

prettycsv is a generator.

class JSMinUnterminatedComment​(Exception):

class JSMinUnterminatedStringLiteral​(Exception):

class JSMinUnterminatedRegularExpression​(Exception):

def jsmin​(input):

Minimizes the Javascript source input.

Alternate versions   Text   XIST   Python