April 24, 2015

Python context manager (not bpy context)

How does the python context manager work

Maybe it's not a 'the context' manager, but 'a' context manager. Either way, for quite a long time i've wanted to make my own. Only today did I get a chance to apply it. The docs are not massive because it isn't a big topic. I have no idea how it works, but as long as it does work we shouldn't need to care how it works under the hood.

Why use a context manager at all?

If used properly it allows you to hide setup and breakdown. But even if you use it in passing as a way to limit the availability of a set of parameters to a narrow scope, it's probably neat -- i don't know i've not had a battle with it yet.

anyway, I think it's cool.
from contextlib import contextmanager

@contextmanager
def surfsup():
    info = lambda: None
    info.breaker = ['teleprompt']
    info.charly = ['humate', 0, 2, 3]
    yield info

with surfsup() as i:
    print(i.breaker)
    print(i.charly)
the parens are optional in the yield and as (args, printer)
from contextlib import contextmanager


def printer(fstr):
    print(fstr * 2)


@contextmanager
def conjunct():
    kn = lambda: None
    kn.do = 'Yes'
    kn.dont = 'No'
    yield (kn, printer)


with conjunct() as (args, printer):
    printer(args.do)
    printer(args.dont)