[PATCH 1 of 8 V2] perf: introduce safeattrsetter to replace direct attribute assignment

Yuya Nishihara yuya at tcha.org
Thu Oct 13 10:50:47 EDT 2016


On Sun, 09 Oct 2016 01:18:21 +0900, FUJIWARA Katsunori wrote:
> # HG changeset patch
> # User FUJIWARA Katsunori <foozy at lares.dti.ne.jp>
> # Date 1475942596 -32400
> #      Sun Oct 09 01:03:16 2016 +0900
> # Node ID a03b967913dd881f750a5848f567d1e0a1d0e7ea
> # Parent  87b8e40eb8125d5ddc848d972b117989346057dd
> perf: introduce safeattrsetter to replace direct attribute assignment

These all look good to me. Queued, many thanks.

> +def safeattrsetter(obj, name, ignoremissing=False):
> +    """Ensure that 'obj' has 'name' attribute before subsequent setattr
> +
> +    This function is aborted, if 'obj' doesn't have 'name' attribute
> +    at runtime. This avoids overlooking removal of an attribute, which
> +    breaks assumption of performance measurement, in the future.
> +
> +    This function returns the object to (1) assign a new value, and
> +    (2) restore an original value to the attribute.
> +
> +    If 'ignoremissing' is true, missing 'name' attribute doesn't cause
> +    abortion, and this function returns None. This is useful to
> +    examine an attribute, which isn't ensured in all Mercurial
> +    versions.
> +    """
> +    if not util.safehasattr(obj, name):
> +        if ignoremissing:
> +            return None
> +        raise error.Abort(("missing attribute %s of %s might break assumption"
> +                           " of performance measurement") % (name, obj))
> +
> +    origvalue = getattr(obj, name)
> +    class attrutil(object):
> +        def set(self, newvalue):
> +            setattr(obj, name, newvalue)
> +        def restore(self):
> +            setattr(obj, name, origvalue)
> +
> +    return attrutil()

This could be a class sefeattrsetter, but we would need to handle ignoremissing
out of its __init__.


More information about the Mercurial-devel mailing list