webhelpers2.misc

Helpers that are neither text, numeric, container, or date.

Data processing

webhelpers2.misc.count_true(seq[, pred])

How many elements is pred(elm) true for?

With the default predicate, this counts the number of true elements.

This is equivalent to the itertools.quantify recipe, which I couldn’t get to work.

webhelpers2.misc.convert(value, type_)

Return the value converted to the type, or None if error.

type_ may be a Python type or any function taking one argument.

webhelpers2.misc.flatten(iterable)

Recursively iterate lists and tuples.

Examples:

>>> list(flatten([1, [2, 3], 4]))
[1, 2, 3, 4]
>>> list(flatten([1, (2, 3, [4]), 5]))
[1, 2, 3, 4, 5]

Image processing

webhelpers2.misc.choose_height(new_width, width, height)

Calculate a proportional height for scaling an image. Given the image’s existing width and height and proposed new width, return the height that preserves the width:height ratio of the original.

Exceptions and deprecation

webhelpers2.misc.deprecate(message, pending=False, stacklevel=2)

Issue a deprecation warning.

message: the deprecation message.

pending: if true, use PendingDeprecationWarning. If false (default), use DeprecationWarning. Python displays deprecations and ignores pending deprecations by default.

stacklevel: passed to warnings.warn. The default level 2 makes the traceback end at the caller’s level. Higher numbers make it end at higher levels.

webhelpers2.misc.format_exception(exc=None)

Format the exception type and value for display, without the traceback.

This is the function you always wished were in the traceback module but isn’t. It’s different from traceback.format_exception, which includes the traceback, returns a list of lines, and has a trailing newline.

If you don’t provide an exception object as an argument, it will call sys.exc_info() to get the current exception.

class webhelpers2.misc.StudlyException(**kw)

A simpler way to define an exception with a message.

To use, subclass and set class attribute m to the message. It may contain placeholders using "{keyword}" syntax.

Instantiate with the same keyword args. It will call self.m.format(**kw) to generate the message, and also set instance attributes corresponding to the keywords. If instantiated without arguments, self.m is the message.

Positional arguments are not accepted. Keyword arg "m" is not accepted either. Either of these raises TypeError.

Examples:

>>> class MyError(StudlyException):
...     m = "can't frob the bar when foo is enabled"
...
>>> raise MyError()
>>> class MyError2(StudlyException):
...     m = "file {filename} not found"
>>> e = MyError2(filename="foo.ini")
>>> print(e.filename)