how to do a conditional decorator in python












20















Is it possible to decorator a function conditionally. For example, I want to decorate the function foo() with a timer function (timeit) only doing_performance_analysis is True (see the psuedo-code below).



if doing_performance_analysis:
@timeit
def foo():
"""
do something, timeit function will return the time it takes
"""
time.sleep(2)
else:
def foo():
time.sleep(2)









share|improve this question





























    20















    Is it possible to decorator a function conditionally. For example, I want to decorate the function foo() with a timer function (timeit) only doing_performance_analysis is True (see the psuedo-code below).



    if doing_performance_analysis:
    @timeit
    def foo():
    """
    do something, timeit function will return the time it takes
    """
    time.sleep(2)
    else:
    def foo():
    time.sleep(2)









    share|improve this question



























      20












      20








      20


      12






      Is it possible to decorator a function conditionally. For example, I want to decorate the function foo() with a timer function (timeit) only doing_performance_analysis is True (see the psuedo-code below).



      if doing_performance_analysis:
      @timeit
      def foo():
      """
      do something, timeit function will return the time it takes
      """
      time.sleep(2)
      else:
      def foo():
      time.sleep(2)









      share|improve this question
















      Is it possible to decorator a function conditionally. For example, I want to decorate the function foo() with a timer function (timeit) only doing_performance_analysis is True (see the psuedo-code below).



      if doing_performance_analysis:
      @timeit
      def foo():
      """
      do something, timeit function will return the time it takes
      """
      time.sleep(2)
      else:
      def foo():
      time.sleep(2)






      python conditional decorator python-decorators






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 2 at 10:04









      Martijn Pieters

      722k14125242333




      722k14125242333










      asked May 23 '12 at 17:20









      cfpetecfpete

      1,38341623




      1,38341623
























          6 Answers
          6






          active

          oldest

          votes


















          31














          Decorators are simply callables that return a replacement, optionally the same function, a wrapper, or something completely different. As such, you could create a conditional decorator:



          def conditional_decorator(dec, condition):
          def decorator(func):
          if not condition:
          # Return the function unchanged, not decorated.
          return func
          return dec(func)
          return decorator


          Now you can use it like this:



          @conditional_decorator(timeit, doing_performance_analysis)
          def foo():
          time.sleep(2)


          The decorator could also be a class:



          class conditional_decorator(object):
          def __init__(self, dec, condition):
          self.decorator = dec
          self.condition = condition

          def __call__(self, func):
          if not self.condition:
          # Return the function unchanged, not decorated.
          return func
          return self.decorator(func)


          Here the __call__ method plays the same role as the returned decorator() nested function in the first example, and the closed-over dec and condition parameters here are stored as arguments on the instance until the decorator is applied.






          share|improve this answer





















          • 1





            Thanks! The comment section does not format, so I added the sample code to your original reply. Can you pls explain why the timing function is not called?

            – cfpete
            May 23 '12 at 19:37






          • 2





            The decorator is applied at import time, so instance variables are not being consulted at that time. You'd have to write a different decorator for that, one that inspects self when called. Out of scope for this Q and comment format. :-)

            – Martijn Pieters
            May 23 '12 at 19:42











          • How would I use it if I want to use this on class based methods, ie Django Class based views. Over there we have to use method_decorator. How to make this code compatible with that?

            – PythonEnthusiast
            Aug 24 '16 at 8:13











          • @PythonEnthusiast: By just passing in the result of the call: @method_decorator(conditional_decorator(timeit, doing_performance_analysis)).

            – Martijn Pieters
            Aug 24 '16 at 10:53



















          9














          A decorator is simply a function applied to another function. You can apply it manually:



          def foo():
          # whatever
          time.sleep(2)

          if doing_performance_analysis:
          foo = timeit(foo)





          share|improve this answer































            4














            How about:



            def foo():
            ...

            if doing_performance_analysis:
            foo = timeit(foo)


            I imagine you could even wrap this into a decorator that would take a boolean flag and another decorator, and would only apply the latter if the flag is set to True:



            def cond_decorator(flag, dec):
            def decorate(fn):
            return dec(fn) if flag else fn
            return decorate

            @cond_decorator(doing_performance_analysis, timeit)
            def foo():
            ...





            share|improve this answer

































              0














              Blckknght's answer is great if you want to do the check every time you call the function, but if you have a setting that you can read once and never changes you may not want to check the setting every time the decorated function is called. In some of our high performance daemons at work I have written a decorator that checks a setting file once when the python file is first loaded and decides if it should wrap it or not.



              Here is a sample



              def timed(f):
              def wrapper(*args, **kwargs):
              start = datetime.datetime.utcnow()
              return_value = f(*args, **kwargs)
              end = datetime.datetime.utcnow()
              duration = end - start

              log_function_call(module=f.__module__, function=f.__name__, start=__start__, end=__end__, duration=duration.total_seconds())
              if config.get('RUN_TIMED_FUNCTIONS'):
              return wrapper
              return f


              Assuming that log_function_call logs your call to a database, logfile, or whatever and that config.get('RUN_TIMED_FUNCTIONS') checks your global configuration, then adding the @timed decorator to a function will check once on load to see if you are timing on this server, environment, etc. and if not then it won't change the execution of the function on production or the other environments where you care about performance.






              share|improve this answer































                0














                use_decorator = False

                class myDecorator(object):
                def __init__(self, f):
                self.f = f

                def __call__(self):
                print "Decorated running..."
                print "Entering", self.f.__name__
                self.f()
                print "Exited", self.f.__name__


                def null(a):
                return a


                if use_decorator == False :
                myDecorator = null


                @myDecorator
                def CoreFunction():
                print "Core Function running"

                CoreFunction()





                share|improve this answer































                  0














                  Here is what worked for me:



                  def timeit(method):
                  def timed(*args, **kw):
                  if 'usetimer' not in kw:
                  return method(*args, **kw)
                  elif ('usetimer' in kw and kw.get('usetimer') is None):
                  return method(*args, **kw)
                  else:
                  import time
                  ts = time.time()
                  result = method(*args, **kw)
                  te = time.time()
                  if 'log_time' in kw:
                  name = kw.get('log_name', method.__name__.upper())
                  kw['log_time'][name] = int((te - ts) * 1000)
                  else:
                  print '%r took %2.2f ms' %
                  (method.__name__, (te - ts) * 1000)
                  return result
                  return timed

                  def some_func(arg1, **kwargs):
                  #do something here

                  some_func(param1, **{'usetimer': args.usetimer})





                  share|improve this answer























                    Your Answer






                    StackExchange.ifUsing("editor", function () {
                    StackExchange.using("externalEditor", function () {
                    StackExchange.using("snippets", function () {
                    StackExchange.snippets.init();
                    });
                    });
                    }, "code-snippets");

                    StackExchange.ready(function() {
                    var channelOptions = {
                    tags: "".split(" "),
                    id: "1"
                    };
                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                    StackExchange.using("externalEditor", function() {
                    // Have to fire editor after snippets, if snippets enabled
                    if (StackExchange.settings.snippets.snippetsEnabled) {
                    StackExchange.using("snippets", function() {
                    createEditor();
                    });
                    }
                    else {
                    createEditor();
                    }
                    });

                    function createEditor() {
                    StackExchange.prepareEditor({
                    heartbeatType: 'answer',
                    autoActivateHeartbeat: false,
                    convertImagesToLinks: true,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: 10,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader: {
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                    allowUrls: true
                    },
                    onDemand: true,
                    discardSelector: ".discard-answer"
                    ,immediatelyShowMarkdownHelp:true
                    });


                    }
                    });














                    draft saved

                    draft discarded


















                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10724854%2fhow-to-do-a-conditional-decorator-in-python%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    6 Answers
                    6






                    active

                    oldest

                    votes








                    6 Answers
                    6






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    31














                    Decorators are simply callables that return a replacement, optionally the same function, a wrapper, or something completely different. As such, you could create a conditional decorator:



                    def conditional_decorator(dec, condition):
                    def decorator(func):
                    if not condition:
                    # Return the function unchanged, not decorated.
                    return func
                    return dec(func)
                    return decorator


                    Now you can use it like this:



                    @conditional_decorator(timeit, doing_performance_analysis)
                    def foo():
                    time.sleep(2)


                    The decorator could also be a class:



                    class conditional_decorator(object):
                    def __init__(self, dec, condition):
                    self.decorator = dec
                    self.condition = condition

                    def __call__(self, func):
                    if not self.condition:
                    # Return the function unchanged, not decorated.
                    return func
                    return self.decorator(func)


                    Here the __call__ method plays the same role as the returned decorator() nested function in the first example, and the closed-over dec and condition parameters here are stored as arguments on the instance until the decorator is applied.






                    share|improve this answer





















                    • 1





                      Thanks! The comment section does not format, so I added the sample code to your original reply. Can you pls explain why the timing function is not called?

                      – cfpete
                      May 23 '12 at 19:37






                    • 2





                      The decorator is applied at import time, so instance variables are not being consulted at that time. You'd have to write a different decorator for that, one that inspects self when called. Out of scope for this Q and comment format. :-)

                      – Martijn Pieters
                      May 23 '12 at 19:42











                    • How would I use it if I want to use this on class based methods, ie Django Class based views. Over there we have to use method_decorator. How to make this code compatible with that?

                      – PythonEnthusiast
                      Aug 24 '16 at 8:13











                    • @PythonEnthusiast: By just passing in the result of the call: @method_decorator(conditional_decorator(timeit, doing_performance_analysis)).

                      – Martijn Pieters
                      Aug 24 '16 at 10:53
















                    31














                    Decorators are simply callables that return a replacement, optionally the same function, a wrapper, or something completely different. As such, you could create a conditional decorator:



                    def conditional_decorator(dec, condition):
                    def decorator(func):
                    if not condition:
                    # Return the function unchanged, not decorated.
                    return func
                    return dec(func)
                    return decorator


                    Now you can use it like this:



                    @conditional_decorator(timeit, doing_performance_analysis)
                    def foo():
                    time.sleep(2)


                    The decorator could also be a class:



                    class conditional_decorator(object):
                    def __init__(self, dec, condition):
                    self.decorator = dec
                    self.condition = condition

                    def __call__(self, func):
                    if not self.condition:
                    # Return the function unchanged, not decorated.
                    return func
                    return self.decorator(func)


                    Here the __call__ method plays the same role as the returned decorator() nested function in the first example, and the closed-over dec and condition parameters here are stored as arguments on the instance until the decorator is applied.






                    share|improve this answer





















                    • 1





                      Thanks! The comment section does not format, so I added the sample code to your original reply. Can you pls explain why the timing function is not called?

                      – cfpete
                      May 23 '12 at 19:37






                    • 2





                      The decorator is applied at import time, so instance variables are not being consulted at that time. You'd have to write a different decorator for that, one that inspects self when called. Out of scope for this Q and comment format. :-)

                      – Martijn Pieters
                      May 23 '12 at 19:42











                    • How would I use it if I want to use this on class based methods, ie Django Class based views. Over there we have to use method_decorator. How to make this code compatible with that?

                      – PythonEnthusiast
                      Aug 24 '16 at 8:13











                    • @PythonEnthusiast: By just passing in the result of the call: @method_decorator(conditional_decorator(timeit, doing_performance_analysis)).

                      – Martijn Pieters
                      Aug 24 '16 at 10:53














                    31












                    31








                    31







                    Decorators are simply callables that return a replacement, optionally the same function, a wrapper, or something completely different. As such, you could create a conditional decorator:



                    def conditional_decorator(dec, condition):
                    def decorator(func):
                    if not condition:
                    # Return the function unchanged, not decorated.
                    return func
                    return dec(func)
                    return decorator


                    Now you can use it like this:



                    @conditional_decorator(timeit, doing_performance_analysis)
                    def foo():
                    time.sleep(2)


                    The decorator could also be a class:



                    class conditional_decorator(object):
                    def __init__(self, dec, condition):
                    self.decorator = dec
                    self.condition = condition

                    def __call__(self, func):
                    if not self.condition:
                    # Return the function unchanged, not decorated.
                    return func
                    return self.decorator(func)


                    Here the __call__ method plays the same role as the returned decorator() nested function in the first example, and the closed-over dec and condition parameters here are stored as arguments on the instance until the decorator is applied.






                    share|improve this answer















                    Decorators are simply callables that return a replacement, optionally the same function, a wrapper, or something completely different. As such, you could create a conditional decorator:



                    def conditional_decorator(dec, condition):
                    def decorator(func):
                    if not condition:
                    # Return the function unchanged, not decorated.
                    return func
                    return dec(func)
                    return decorator


                    Now you can use it like this:



                    @conditional_decorator(timeit, doing_performance_analysis)
                    def foo():
                    time.sleep(2)


                    The decorator could also be a class:



                    class conditional_decorator(object):
                    def __init__(self, dec, condition):
                    self.decorator = dec
                    self.condition = condition

                    def __call__(self, func):
                    if not self.condition:
                    # Return the function unchanged, not decorated.
                    return func
                    return self.decorator(func)


                    Here the __call__ method plays the same role as the returned decorator() nested function in the first example, and the closed-over dec and condition parameters here are stored as arguments on the instance until the decorator is applied.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Sep 27 '18 at 13:06

























                    answered May 23 '12 at 17:24









                    Martijn PietersMartijn Pieters

                    722k14125242333




                    722k14125242333








                    • 1





                      Thanks! The comment section does not format, so I added the sample code to your original reply. Can you pls explain why the timing function is not called?

                      – cfpete
                      May 23 '12 at 19:37






                    • 2





                      The decorator is applied at import time, so instance variables are not being consulted at that time. You'd have to write a different decorator for that, one that inspects self when called. Out of scope for this Q and comment format. :-)

                      – Martijn Pieters
                      May 23 '12 at 19:42











                    • How would I use it if I want to use this on class based methods, ie Django Class based views. Over there we have to use method_decorator. How to make this code compatible with that?

                      – PythonEnthusiast
                      Aug 24 '16 at 8:13











                    • @PythonEnthusiast: By just passing in the result of the call: @method_decorator(conditional_decorator(timeit, doing_performance_analysis)).

                      – Martijn Pieters
                      Aug 24 '16 at 10:53














                    • 1





                      Thanks! The comment section does not format, so I added the sample code to your original reply. Can you pls explain why the timing function is not called?

                      – cfpete
                      May 23 '12 at 19:37






                    • 2





                      The decorator is applied at import time, so instance variables are not being consulted at that time. You'd have to write a different decorator for that, one that inspects self when called. Out of scope for this Q and comment format. :-)

                      – Martijn Pieters
                      May 23 '12 at 19:42











                    • How would I use it if I want to use this on class based methods, ie Django Class based views. Over there we have to use method_decorator. How to make this code compatible with that?

                      – PythonEnthusiast
                      Aug 24 '16 at 8:13











                    • @PythonEnthusiast: By just passing in the result of the call: @method_decorator(conditional_decorator(timeit, doing_performance_analysis)).

                      – Martijn Pieters
                      Aug 24 '16 at 10:53








                    1




                    1





                    Thanks! The comment section does not format, so I added the sample code to your original reply. Can you pls explain why the timing function is not called?

                    – cfpete
                    May 23 '12 at 19:37





                    Thanks! The comment section does not format, so I added the sample code to your original reply. Can you pls explain why the timing function is not called?

                    – cfpete
                    May 23 '12 at 19:37




                    2




                    2





                    The decorator is applied at import time, so instance variables are not being consulted at that time. You'd have to write a different decorator for that, one that inspects self when called. Out of scope for this Q and comment format. :-)

                    – Martijn Pieters
                    May 23 '12 at 19:42





                    The decorator is applied at import time, so instance variables are not being consulted at that time. You'd have to write a different decorator for that, one that inspects self when called. Out of scope for this Q and comment format. :-)

                    – Martijn Pieters
                    May 23 '12 at 19:42













                    How would I use it if I want to use this on class based methods, ie Django Class based views. Over there we have to use method_decorator. How to make this code compatible with that?

                    – PythonEnthusiast
                    Aug 24 '16 at 8:13





                    How would I use it if I want to use this on class based methods, ie Django Class based views. Over there we have to use method_decorator. How to make this code compatible with that?

                    – PythonEnthusiast
                    Aug 24 '16 at 8:13













                    @PythonEnthusiast: By just passing in the result of the call: @method_decorator(conditional_decorator(timeit, doing_performance_analysis)).

                    – Martijn Pieters
                    Aug 24 '16 at 10:53





                    @PythonEnthusiast: By just passing in the result of the call: @method_decorator(conditional_decorator(timeit, doing_performance_analysis)).

                    – Martijn Pieters
                    Aug 24 '16 at 10:53













                    9














                    A decorator is simply a function applied to another function. You can apply it manually:



                    def foo():
                    # whatever
                    time.sleep(2)

                    if doing_performance_analysis:
                    foo = timeit(foo)





                    share|improve this answer




























                      9














                      A decorator is simply a function applied to another function. You can apply it manually:



                      def foo():
                      # whatever
                      time.sleep(2)

                      if doing_performance_analysis:
                      foo = timeit(foo)





                      share|improve this answer


























                        9












                        9








                        9







                        A decorator is simply a function applied to another function. You can apply it manually:



                        def foo():
                        # whatever
                        time.sleep(2)

                        if doing_performance_analysis:
                        foo = timeit(foo)





                        share|improve this answer













                        A decorator is simply a function applied to another function. You can apply it manually:



                        def foo():
                        # whatever
                        time.sleep(2)

                        if doing_performance_analysis:
                        foo = timeit(foo)






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered May 23 '12 at 17:23









                        BlckknghtBlckknght

                        64.4k557107




                        64.4k557107























                            4














                            How about:



                            def foo():
                            ...

                            if doing_performance_analysis:
                            foo = timeit(foo)


                            I imagine you could even wrap this into a decorator that would take a boolean flag and another decorator, and would only apply the latter if the flag is set to True:



                            def cond_decorator(flag, dec):
                            def decorate(fn):
                            return dec(fn) if flag else fn
                            return decorate

                            @cond_decorator(doing_performance_analysis, timeit)
                            def foo():
                            ...





                            share|improve this answer






























                              4














                              How about:



                              def foo():
                              ...

                              if doing_performance_analysis:
                              foo = timeit(foo)


                              I imagine you could even wrap this into a decorator that would take a boolean flag and another decorator, and would only apply the latter if the flag is set to True:



                              def cond_decorator(flag, dec):
                              def decorate(fn):
                              return dec(fn) if flag else fn
                              return decorate

                              @cond_decorator(doing_performance_analysis, timeit)
                              def foo():
                              ...





                              share|improve this answer




























                                4












                                4








                                4







                                How about:



                                def foo():
                                ...

                                if doing_performance_analysis:
                                foo = timeit(foo)


                                I imagine you could even wrap this into a decorator that would take a boolean flag and another decorator, and would only apply the latter if the flag is set to True:



                                def cond_decorator(flag, dec):
                                def decorate(fn):
                                return dec(fn) if flag else fn
                                return decorate

                                @cond_decorator(doing_performance_analysis, timeit)
                                def foo():
                                ...





                                share|improve this answer















                                How about:



                                def foo():
                                ...

                                if doing_performance_analysis:
                                foo = timeit(foo)


                                I imagine you could even wrap this into a decorator that would take a boolean flag and another decorator, and would only apply the latter if the flag is set to True:



                                def cond_decorator(flag, dec):
                                def decorate(fn):
                                return dec(fn) if flag else fn
                                return decorate

                                @cond_decorator(doing_performance_analysis, timeit)
                                def foo():
                                ...






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited May 23 '12 at 17:27

























                                answered May 23 '12 at 17:22









                                NPENPE

                                356k67759889




                                356k67759889























                                    0














                                    Blckknght's answer is great if you want to do the check every time you call the function, but if you have a setting that you can read once and never changes you may not want to check the setting every time the decorated function is called. In some of our high performance daemons at work I have written a decorator that checks a setting file once when the python file is first loaded and decides if it should wrap it or not.



                                    Here is a sample



                                    def timed(f):
                                    def wrapper(*args, **kwargs):
                                    start = datetime.datetime.utcnow()
                                    return_value = f(*args, **kwargs)
                                    end = datetime.datetime.utcnow()
                                    duration = end - start

                                    log_function_call(module=f.__module__, function=f.__name__, start=__start__, end=__end__, duration=duration.total_seconds())
                                    if config.get('RUN_TIMED_FUNCTIONS'):
                                    return wrapper
                                    return f


                                    Assuming that log_function_call logs your call to a database, logfile, or whatever and that config.get('RUN_TIMED_FUNCTIONS') checks your global configuration, then adding the @timed decorator to a function will check once on load to see if you are timing on this server, environment, etc. and if not then it won't change the execution of the function on production or the other environments where you care about performance.






                                    share|improve this answer




























                                      0














                                      Blckknght's answer is great if you want to do the check every time you call the function, but if you have a setting that you can read once and never changes you may not want to check the setting every time the decorated function is called. In some of our high performance daemons at work I have written a decorator that checks a setting file once when the python file is first loaded and decides if it should wrap it or not.



                                      Here is a sample



                                      def timed(f):
                                      def wrapper(*args, **kwargs):
                                      start = datetime.datetime.utcnow()
                                      return_value = f(*args, **kwargs)
                                      end = datetime.datetime.utcnow()
                                      duration = end - start

                                      log_function_call(module=f.__module__, function=f.__name__, start=__start__, end=__end__, duration=duration.total_seconds())
                                      if config.get('RUN_TIMED_FUNCTIONS'):
                                      return wrapper
                                      return f


                                      Assuming that log_function_call logs your call to a database, logfile, or whatever and that config.get('RUN_TIMED_FUNCTIONS') checks your global configuration, then adding the @timed decorator to a function will check once on load to see if you are timing on this server, environment, etc. and if not then it won't change the execution of the function on production or the other environments where you care about performance.






                                      share|improve this answer


























                                        0












                                        0








                                        0







                                        Blckknght's answer is great if you want to do the check every time you call the function, but if you have a setting that you can read once and never changes you may not want to check the setting every time the decorated function is called. In some of our high performance daemons at work I have written a decorator that checks a setting file once when the python file is first loaded and decides if it should wrap it or not.



                                        Here is a sample



                                        def timed(f):
                                        def wrapper(*args, **kwargs):
                                        start = datetime.datetime.utcnow()
                                        return_value = f(*args, **kwargs)
                                        end = datetime.datetime.utcnow()
                                        duration = end - start

                                        log_function_call(module=f.__module__, function=f.__name__, start=__start__, end=__end__, duration=duration.total_seconds())
                                        if config.get('RUN_TIMED_FUNCTIONS'):
                                        return wrapper
                                        return f


                                        Assuming that log_function_call logs your call to a database, logfile, or whatever and that config.get('RUN_TIMED_FUNCTIONS') checks your global configuration, then adding the @timed decorator to a function will check once on load to see if you are timing on this server, environment, etc. and if not then it won't change the execution of the function on production or the other environments where you care about performance.






                                        share|improve this answer













                                        Blckknght's answer is great if you want to do the check every time you call the function, but if you have a setting that you can read once and never changes you may not want to check the setting every time the decorated function is called. In some of our high performance daemons at work I have written a decorator that checks a setting file once when the python file is first loaded and decides if it should wrap it or not.



                                        Here is a sample



                                        def timed(f):
                                        def wrapper(*args, **kwargs):
                                        start = datetime.datetime.utcnow()
                                        return_value = f(*args, **kwargs)
                                        end = datetime.datetime.utcnow()
                                        duration = end - start

                                        log_function_call(module=f.__module__, function=f.__name__, start=__start__, end=__end__, duration=duration.total_seconds())
                                        if config.get('RUN_TIMED_FUNCTIONS'):
                                        return wrapper
                                        return f


                                        Assuming that log_function_call logs your call to a database, logfile, or whatever and that config.get('RUN_TIMED_FUNCTIONS') checks your global configuration, then adding the @timed decorator to a function will check once on load to see if you are timing on this server, environment, etc. and if not then it won't change the execution of the function on production or the other environments where you care about performance.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Jan 16 '14 at 22:15









                                        noblednobled

                                        8527




                                        8527























                                            0














                                            use_decorator = False

                                            class myDecorator(object):
                                            def __init__(self, f):
                                            self.f = f

                                            def __call__(self):
                                            print "Decorated running..."
                                            print "Entering", self.f.__name__
                                            self.f()
                                            print "Exited", self.f.__name__


                                            def null(a):
                                            return a


                                            if use_decorator == False :
                                            myDecorator = null


                                            @myDecorator
                                            def CoreFunction():
                                            print "Core Function running"

                                            CoreFunction()





                                            share|improve this answer




























                                              0














                                              use_decorator = False

                                              class myDecorator(object):
                                              def __init__(self, f):
                                              self.f = f

                                              def __call__(self):
                                              print "Decorated running..."
                                              print "Entering", self.f.__name__
                                              self.f()
                                              print "Exited", self.f.__name__


                                              def null(a):
                                              return a


                                              if use_decorator == False :
                                              myDecorator = null


                                              @myDecorator
                                              def CoreFunction():
                                              print "Core Function running"

                                              CoreFunction()





                                              share|improve this answer


























                                                0












                                                0








                                                0







                                                use_decorator = False

                                                class myDecorator(object):
                                                def __init__(self, f):
                                                self.f = f

                                                def __call__(self):
                                                print "Decorated running..."
                                                print "Entering", self.f.__name__
                                                self.f()
                                                print "Exited", self.f.__name__


                                                def null(a):
                                                return a


                                                if use_decorator == False :
                                                myDecorator = null


                                                @myDecorator
                                                def CoreFunction():
                                                print "Core Function running"

                                                CoreFunction()





                                                share|improve this answer













                                                use_decorator = False

                                                class myDecorator(object):
                                                def __init__(self, f):
                                                self.f = f

                                                def __call__(self):
                                                print "Decorated running..."
                                                print "Entering", self.f.__name__
                                                self.f()
                                                print "Exited", self.f.__name__


                                                def null(a):
                                                return a


                                                if use_decorator == False :
                                                myDecorator = null


                                                @myDecorator
                                                def CoreFunction():
                                                print "Core Function running"

                                                CoreFunction()






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Sep 17 '16 at 0:10









                                                Lawrence CherninLawrence Chernin

                                                7329




                                                7329























                                                    0














                                                    Here is what worked for me:



                                                    def timeit(method):
                                                    def timed(*args, **kw):
                                                    if 'usetimer' not in kw:
                                                    return method(*args, **kw)
                                                    elif ('usetimer' in kw and kw.get('usetimer') is None):
                                                    return method(*args, **kw)
                                                    else:
                                                    import time
                                                    ts = time.time()
                                                    result = method(*args, **kw)
                                                    te = time.time()
                                                    if 'log_time' in kw:
                                                    name = kw.get('log_name', method.__name__.upper())
                                                    kw['log_time'][name] = int((te - ts) * 1000)
                                                    else:
                                                    print '%r took %2.2f ms' %
                                                    (method.__name__, (te - ts) * 1000)
                                                    return result
                                                    return timed

                                                    def some_func(arg1, **kwargs):
                                                    #do something here

                                                    some_func(param1, **{'usetimer': args.usetimer})





                                                    share|improve this answer




























                                                      0














                                                      Here is what worked for me:



                                                      def timeit(method):
                                                      def timed(*args, **kw):
                                                      if 'usetimer' not in kw:
                                                      return method(*args, **kw)
                                                      elif ('usetimer' in kw and kw.get('usetimer') is None):
                                                      return method(*args, **kw)
                                                      else:
                                                      import time
                                                      ts = time.time()
                                                      result = method(*args, **kw)
                                                      te = time.time()
                                                      if 'log_time' in kw:
                                                      name = kw.get('log_name', method.__name__.upper())
                                                      kw['log_time'][name] = int((te - ts) * 1000)
                                                      else:
                                                      print '%r took %2.2f ms' %
                                                      (method.__name__, (te - ts) * 1000)
                                                      return result
                                                      return timed

                                                      def some_func(arg1, **kwargs):
                                                      #do something here

                                                      some_func(param1, **{'usetimer': args.usetimer})





                                                      share|improve this answer


























                                                        0












                                                        0








                                                        0







                                                        Here is what worked for me:



                                                        def timeit(method):
                                                        def timed(*args, **kw):
                                                        if 'usetimer' not in kw:
                                                        return method(*args, **kw)
                                                        elif ('usetimer' in kw and kw.get('usetimer') is None):
                                                        return method(*args, **kw)
                                                        else:
                                                        import time
                                                        ts = time.time()
                                                        result = method(*args, **kw)
                                                        te = time.time()
                                                        if 'log_time' in kw:
                                                        name = kw.get('log_name', method.__name__.upper())
                                                        kw['log_time'][name] = int((te - ts) * 1000)
                                                        else:
                                                        print '%r took %2.2f ms' %
                                                        (method.__name__, (te - ts) * 1000)
                                                        return result
                                                        return timed

                                                        def some_func(arg1, **kwargs):
                                                        #do something here

                                                        some_func(param1, **{'usetimer': args.usetimer})





                                                        share|improve this answer













                                                        Here is what worked for me:



                                                        def timeit(method):
                                                        def timed(*args, **kw):
                                                        if 'usetimer' not in kw:
                                                        return method(*args, **kw)
                                                        elif ('usetimer' in kw and kw.get('usetimer') is None):
                                                        return method(*args, **kw)
                                                        else:
                                                        import time
                                                        ts = time.time()
                                                        result = method(*args, **kw)
                                                        te = time.time()
                                                        if 'log_time' in kw:
                                                        name = kw.get('log_name', method.__name__.upper())
                                                        kw['log_time'][name] = int((te - ts) * 1000)
                                                        else:
                                                        print '%r took %2.2f ms' %
                                                        (method.__name__, (te - ts) * 1000)
                                                        return result
                                                        return timed

                                                        def some_func(arg1, **kwargs):
                                                        #do something here

                                                        some_func(param1, **{'usetimer': args.usetimer})






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Nov 21 '18 at 14:23









                                                        user336558user336558

                                                        1616




                                                        1616






























                                                            draft saved

                                                            draft discarded




















































                                                            Thanks for contributing an answer to Stack Overflow!


                                                            • Please be sure to answer the question. Provide details and share your research!

                                                            But avoid



                                                            • Asking for help, clarification, or responding to other answers.

                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                            To learn more, see our tips on writing great answers.




                                                            draft saved


                                                            draft discarded














                                                            StackExchange.ready(
                                                            function () {
                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f10724854%2fhow-to-do-a-conditional-decorator-in-python%23new-answer', 'question_page');
                                                            }
                                                            );

                                                            Post as a guest















                                                            Required, but never shown





















































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown

































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown







                                                            Popular posts from this blog

                                                            Can a sorcerer learn a 5th-level spell early by creating spell slots using the Font of Magic feature?

                                                            ts Property 'filter' does not exist on type '{}'

                                                            mat-slide-toggle shouldn't change it's state when I click cancel in confirmation window