advice about `correct' use of decorator

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Aug 22 10:13:21 EDT 2007


On 22 ago, 10:00, "BJörn Lindqvist" <bjou... at gmail.com> wrote:
> On 8/17/07, Gerardo Herzig <gher... at fmed.uba.ar> wrote:
>
> > BJörn Lindqvist wrote:
> > >def is_logued_in():
> > >    if not user.is_logged_in():
> > >        raise NotLoggedInError
>
> > >It costs you one more line, but reduces complexity. And if you are
> > >worried about that extra line you can put it in a function.
>
> > As far as i know (by the way, AFAK is the shortcut?, and BTW means `by
> > the way'? ), decorators are not indispensable. I mean, all that you can
> > do with python, you can doit without decorators. And from my point of
> > view, this hides the complexity for the other developers of my group,
>
> hiding is not the same thing as reducing. By hiding the code behind a
> decorator, you are increasing the complexity by adding another layer
> that the programmer has to look through to see your control flow.
>
> > since all they have to do is add the @is_logged_in line at the top of
> > the cgi script, and not to worrie about exceptions, not even how the
> > decorator is implemented (i may log the error in some file). All they
> > have to know is that any abnormal situation will redirect to the `login'
> > screen.
>
> As I said, you can accomplish the exact same thing by calling a
> function from within the function that requires the user to be logged
> in.
>
> def change_pass():
>     check_user_logged_in()
>     ... more stuff here...
>
> is less complex (and therefore preferable) than:
>
> @check_user_logged_in
> def change_pass():
>     ... more stuff here...
>
> An important principle in engineering is that you should always strive
> to make your design as simple as possible. If you have two equal
> designs, you should always choose the one that is simpler because
> simple things are easier to understand than complex things.

I don't see the complexity in this case - both are a single line of
code. Any internal complexity is hidden by the language. In fact, I
consider the decorated function simpler than the other: its body
represents exactly what the function does, without any distracting
precondition calls.
The decorator has some advantages: can have syntax support on your
editor, can perform some registering/logging, it's even easier to
quickly check visually if it's here.

--
Gabriel Genellina




More information about the Python-list mailing list