Python Forum
Decorator inhibits execution of function if non-None parameter not supplied - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code sharing (https://python-forum.io/forum-5.html)
+--- Thread: Decorator inhibits execution of function if non-None parameter not supplied (/thread-8547.html)



Decorator inhibits execution of function if non-None parameter not supplied - league55 - Feb-25-2018

If a function is supposed to receive a parameter other than None, but for whatever reason the value of the parameter is None, this decorator will inhibit the function from executing. Very useful when required command line arguments are missing. Don't forget to import sys!

Here's the decorator:

def none_decorator(func):
    def none_deco(*args):
        if len(sys.argv) > 1:
            return func(*args)
    return none_deco
And a potential application:

@none_decorator
def some_function(some_non_none_parameter):
    #put some code here



RE: Decorator inhibits execution of function if non-None parameter not supplied - micseydel - Feb-26-2018

I'm confused. From what you're saying, it sounds like the behavior should vary based on the contents of args, however it's only based on the length of sys.argv, which doesn't make sense to me from your description (partly because sys.argv will be shorter, not contain None).

Could you provide multiple sample cases where this code's behavior is demonstrated? Also, you probably want to pass along **kwargs as well as *args.