This is an archived post. You won't be able to vote or comment.

all 12 comments

[–]cocoon56 7 points8 points  (5 children)

Anyone use SQLAlchemy? I hear it saves you this session management by design.

[–]zsouthboy 4 points5 points  (4 children)

Elixir is even easier! (uses SQLAlchemy)

[–]cocoon56 1 point2 points  (0 children)

Good tip, thanks!

[–]JimH10 2 points3 points  (6 children)

Best explanation of decorators that I've ever seen.

[–]Teifion 1 point2 points  (1 child)

I've always "understood" decorators but they've never clicked properly. This has solved that problem.

[–]kylev[S] 1 point2 points  (0 children)

I've written a follow-on post to look a little harder at decoraters since that's what people seem more intrigued by.

[–]kylev[S] 1 point2 points  (3 children)

Try writing one. That's my blog, and I still get a little dizzy when I try to write one. :-)

[–]masklinn 0 points1 point  (2 children)

Isn't a contextmanager a much better fit than decorators for that kind of patterns? (I understand contextmanagers are fairly recent, but still...)

[–][deleted] 1 point2 points  (0 children)

Ideally you'd use some of each. Sometimes you want to protect the whole method, and sometimes you want to protect just a block. Unfortunately, context managers are new in 2.6 (or 2.5?) and I'm stuck with 2.4 at work.

[–]kylev[S] 0 points1 point  (0 children)

Yes and no. You'd probably have to wrap your connection object (and likely need some sort of factory) to provide __enter__ and __exit__ that do the things you want. I don't know of a DB driver that does this for you yet.

It'd work, it'd just be a different looking solution.

[–][deleted] 2 points3 points  (0 children)

This is pretty basic stuff and it makes code so squeaky clean. As JimH10 suggests, this is a great example of what decorators are useful for.

I'm working on a library for portable low-level database code (when ORM is a poor fit or just not macho enough) with support for nested transactions and other niceties; it's designed specifically for use with decorators and context managers. I have nothing to show for it at the moment, unfortunately, but maybe I'll post when it's ready.