advice about `correct' use of decorator

BJörn Lindqvist bjourne at gmail.com
Wed Aug 22 09:00:15 EDT 2007


On 8/17/07, Gerardo Herzig <gherzig 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.


-- 
mvh Björn



More information about the Python-list mailing list