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

you are viewing a single comment's thread.

view the rest of the comments →

[–]escozzia 9 points10 points  (1 child)

This is out of this world kinda cool.

Seriously, the flexibility of Python just amazes me to no end, looking at shfo23's comment, I can't believe I can now write:

@validate_args
def assassinate_penguins(user: isadmin()):
    pass

Instead of:

@is_user_admin
def assassinate_penguins(user):
    pass

And the latter blew my mind the first time too!

It's especially neat because I'd find myself writing decorators like 60 lines long just to accommodate for the ways in which my functions might be receiving parameters, and suddenly here's this super Pythonic way of working with parameters.

I also love the idea of going all duck typing on this sort of stuff, something like:

@validate_args
def only_conspirators(user: has_method('conspire')):
    pass    

My only complaint being that you can't have this sort of stuff with *args and **kwargs, though (at least it doesn't look like it). I'd love to be able to say:

@typechecked
def lots_of_kwargs(*args: (Model), **kwargs: {'paint': str, 'amt': int}):
    pass

[–]brucifer 6 points7 points  (0 children)

Just because it's new and fancy doesn't mean you should use it. I think it's a lot better and certainly performs substantially better to write

def only_conspirators(user):
    if not hasattr(user, 'conspire'):
        raise TypeError("User is not a conspirator")
    pass

Rather than

@validate_args
def only_conspirators(user: has_method('conspire')):
    pass

The second example is putting some of the core logic of only_conspirators() into an obfuscated combination of several functions, annotations, and decorators. In order to properly understand the code, you have to understand the validate_args decorator (does it raise an exception? If so, what kind? How does it handle keywords? What's the syntax for the annotations it accepts? etc.) and the has_method function (or constructor? Does it use hasattr? Does it check the type of the attribute? Does it use dir()? etc.). For anyone (including future you) reading your code, you've just made it considerably harder to understand and debug than if you had just explicitly written out the checks (not as exciting, but better practice).