_util module

pyflyby._util.AdviceCtx(joinpoint, hook)
class pyflyby._util.Aspect(joinpoint)

Monkey-patch a target method (joinpoint) with “around” advice.

The advice can call “__original__(…)”. At run time, a global named “__original__” will magically be available to the wrapped function. This refers to the original function.

Suppose someone else wrote Foo.bar():

>>> class Foo(object):
...     def __init__(self, x):
...         self.x = x
...     def bar(self, y):
...         return "bar(self.x=%s,y=%s)" % (self.x,y)

>>> foo = Foo(42)

To monkey patch foo.bar, decorate the wrapper with "@advise(foo.bar)":

>>> @advise(foo.bar)
... def addthousand(y):
...     return "advised foo.bar(y=%s): %s" % (y, __original__(y+1000))

>>> foo.bar(100)
'advised foo.bar(y=100): bar(self.x=42,y=1100)'

You can uninstall the advice and get the original behavior back:

>>> addthousand.unadvise()

>>> foo.bar(100)
'bar(self.x=42,y=100)'
See:

http://en.wikipedia.org/wiki/Aspect-oriented_programming

_wrapper = None
advise(hook, once=False)
unadvise()
pyflyby._util.CwdCtx(path)

Context manager that temporarily enters a new working directory.

pyflyby._util.EnvVarCtx(**kwargs)

Context manager that temporarily modifies os.environ.

pyflyby._util.ExcludeImplicitCwdFromPathCtx()

Context manager that temporarily removes “.” from sys.path.

class pyflyby._util.FunctionWithGlobals(function, **variables)

A callable that at runtime adds extra variables to the target function’s global namespace.

This is written as a class with a __call__ method. We do so rather than using a metafunction, so that we can also implement __getattr__ to look through to the target.

pyflyby._util.ImportPathCtx(path_additions)

Context manager that temporarily prepends sys.path with path_additions.

pyflyby._util.NullCtx()

Context manager that does nothing.

exception pyflyby._util.WrappedAttributeError
class pyflyby._util._WritableDictProxy(cls)

Writable equivalent of cls.__dict__.

get(k, default=None)
pyflyby._util.advise(joinpoint)

Advise joinpoint.

See Aspect.

pyflyby._util.cmp(a, b)
pyflyby._util.indent(lines, prefix)
>>> indent('hello\nworld\n', '@@')
'@@hello\n@@world\n'
pyflyby._util.longest_common_prefix(items1, items2)

Return the longest common prefix.

>>> longest_common_prefix("abcde", "abcxy")
'abc'
Return type:

type(items1)

pyflyby._util.nested(*mgrs)
pyflyby._util.partition(iterable, predicate)
>>> partition('12321233221', lambda c: int(c) % 2 == 0)
(['2', '2', '2', '2', '2'], ['1', '3', '1', '3', '3', '1'])
pyflyby._util.prefixes(parts)
>>> list(prefixes("abcd"))
['a', 'ab', 'abc', 'abcd']
pyflyby._util.stable_unique(items)

Return a copy of items without duplicates. The order of other items is unchanged.

>>> stable_unique([1,4,6,4,6,5,7])
[1, 4, 6, 5, 7]