Am 11.09.2012 05:46 schrieb Steven D'Aprano:

Good for you. (Sorry, that comes across as more condescending than it is
intended as.) Monkey-patching often gets used for quick scripts and tiny
pieces of code because it works.

Just beware that if you extend that technique to larger bodies of code,
say when using a large framework, or multiple libraries, your experience
may not be quite so good. Especially if *they* are monkey-patching too,
as some very large frameworks sometimes do. (Or so I am lead to believe.)

This sonds like a good use case for a context manager, like the one in decimal.Context.get_manager().

First shot:

@contextlib.contextmanager
def changed_os_path(**k):
    old = {}
    try:
        for i in k.items():
            old[i] = getattr(os.path, i)
            setattr(os.path, i, k[i])
        yield None
    finally:
        for i in k.items():
            setattr(os.path, i, old[i])

and so for your code you can use

    print 'os.walk(\'goo\') with modified isdir()'
    with changed_os_path(isdir=my_isdir):
        for root, dirs, files in os.walk('goo'):
            print root, dirs, files

so the change is only effective as long as you are in the relevant code part and is reverted as soon as you leave it.


Thomas
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to