trac.util – General purpose utilities

The trac.util package is a hodgepodge of various categories of utilities. If a category contains enough code in itself, it earns a sub-module on its own, like the following ones:

Otherwise, the functions are direct members of the trac.util package (i.e. placed in the “__init__.py” file).

Python “system” utilities

Complements the inspect, traceback and sys modules.

trac.util.fq_class_name(obj)

Return the fully qualified class name of given object.

trac.util.arity(f)

Return the number of arguments expected by the given function, unbound or bound method.

trac.util.get_last_traceback()

Retrieve the last traceback as an unicode string.

trac.util.get_lines_from_file(filename, lineno, context=0, globals=None)

Return content number of lines before and after the specified lineno from the (source code) file identified by filename.

Returns a (lines_before, line, lines_after) tuple.

trac.util.get_frame_info(tb)

Return frame information for a traceback.

trac.util.import_namespace(globals_dict, module_name)

Import the namespace of a module into a globals dict.

This function is used in stub modules to import all symbols defined in another module into the global namespace of the stub, usually for backward compatibility.

trac.util.safe__import__(module_name)

Safe imports: rollback after a failed import.

Initially inspired from the RollbackImporter in PyUnit, but it’s now much simpler and works better for our needs.

See http://pyunit.sourceforge.net/notes/reloading.html

trac.util.safe_repr(x)

repr replacement which “never” breaks.

Make sure we always get a representation of the input x without risking to trigger an exception (e.g. from a buggy x.__repr__).

New in version 1.0.

trac.util.get_doc(obj)

Return the docstring of an object as a tuple (summary, description), where summary is the first paragraph and description is the remaining text.

Setuptools utilities

trac.util.get_module_path(module)

Return the base path the given module is imported from

trac.util.get_sources(path)

Return a dictionary mapping Python module source paths to the distributions that contain them.

trac.util.get_pkginfo(dist)

Get a dictionary containing package information for a package

dist can be either a Distribution instance or, as a shortcut, directly the module instance, if one can safely infer a Distribution instance from it.

Always returns a dictionary but it will be empty if no Distribution instance can be created for the given module.

Data structures which don’t fit anywhere else

class trac.util.Ranges(r=None, reorder=False)

Bases: object

Holds information about ranges parsed from a string

Author:Tim Hatch
>>> x = Ranges("1,2,9-15")
>>> 1 in x
True
>>> 5 in x
False
>>> 10 in x
True
>>> 16 in x
False
>>> [i for i in xrange(20) if i in x]
[1, 2, 9, 10, 11, 12, 13, 14, 15]

Also supports iteration, which makes that last example a bit simpler:

>>> list(x)
[1, 2, 9, 10, 11, 12, 13, 14, 15]

Note that it automatically reduces the list and short-circuits when the desired ranges are a relatively small portion of the entire set:

>>> x = Ranges("99")
>>> 1 in x # really fast
False
>>> x = Ranges("1, 2, 1-2, 2") # reduces this to 1-2
>>> x.pairs
[(1, 2)]
>>> x = Ranges("1-9,2-4") # handle ranges that completely overlap
>>> list(x)
[1, 2, 3, 4, 5, 6, 7, 8, 9]

The members ‘a’ and ‘b’ refer to the min and max value of the range, and are None if the range is empty:

>>> x.a
1
>>> x.b
9
>>> e = Ranges()
>>> e.a, e.b
(None, None)

Empty ranges are ok, and ranges can be constructed in pieces, if you so choose:

>>> x = Ranges()
>>> x.appendrange("1, 2, 3")
>>> x.appendrange("5-9")
>>> x.appendrange("2-3") # reduce'd away
>>> list(x)
[1, 2, 3, 5, 6, 7, 8, 9]

Reversed ranges are ignored, unless the Ranges has the reorder property set.

>>> str(Ranges("20-10"))
''
>>> str(Ranges("20-10", reorder=True))
'10-20'

As rendered ranges are often using u’,u200b’ (comma + Zero-width space) to enable wrapping, we also support reading such ranges, as they can be copy/pasted back.

>>> str(Ranges(u'1,\u200b3,\u200b5,\u200b6,\u200b7,\u200b9'))
'1,3,5-7,9'
appendrange(r)

Add ranges to the current one.

A range is specified as a string of the form “low-high”, and r can be a list of such strings, a string containing comma-separated ranges, or None.

truncate(max)

Truncate the Ranges by setting a maximal allowed value.

Note that this max can be a value in a gap, so the only guarantee is that self.b will be lesser than or equal to max.

>>> r = Ranges("10-20,25-45")
>>> str(r.truncate(30))
'10-20,25-30'
>>> str(r.truncate(22))
'10-20'
>>> str(r.truncate(10))
'10'
trac.util.create_zipinfo(filename, mtime=None, dir=False, executable=False, symlink=False, comment=None)

Create a instance of ZipInfo.

Parameters:
  • filename – file name of the entry
  • mtime – modified time of the entry
  • dir – if True, the entry is a directory
  • executable – if True, the entry is a executable file
  • symlink – if True, the entry is a symbolic link
  • comment – comment of the entry
trac.util.to_ranges(revs)

Converts a list of revisions to a minimal set of ranges.

>>> to_ranges([2, 12, 3, 6, 9, 1, 5, 11])
'1-3,5-6,9,11-12'
>>> to_ranges([])
''
trac.util.to_list(splittable, sep=', ')

Split a string at sep and return a list without any empty items.

>>> to_list('1,2, 3,4 ')
['1', '2', '3', '4']
>>> to_list('1;2; 3;4 ', sep=';')
['1', '2', '3', '4']
>>> to_list('')
[]
>>> to_list(None)
[]
>>> to_list([])
[]
class trac.util.lazy(fn)

Bases: object

A lazily-evaluated attribute.

Since:1.0

Algorithmic utilities

trac.util.embedded_numbers(s)

Comparison function for natural order sorting based on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/214202.

trac.util.partition(iterable, order=None)
>>> partition([(1, "a"), (2, "b"), (3, "a")])
{'a': [1, 3], 'b': [2]}
>>> partition([(1, "a"), (2, "b"), (3, "a")], "ab")
[[1, 3], [2]]
trac.util.as_int(s, default, min=None, max=None)

Convert s to an int and limit it to the given range, or return default if unsuccessful.

trac.util.as_bool(value, default=False)

Convert the given value to a bool.

If value is a string, return True for any of “yes”, “true”, “enabled”, “on” or non-zero numbers, ignoring case. For non-string arguments, return the argument converted to a bool, or default if the conversion fails.

Since 1.2:the default argument can be specified.
trac.util.pathjoin(*args)

Strip / from the arguments and join them with a single /.

trac.util.sub_val(the_list, item_to_remove, item_to_add)

Substitute an item if the item is found in a list, otherwise leave the list unmodified.