0

I've got a condition like the following:

if limit > current and expensive_function() is not None:
    logging.debug('Limit:%s Current:%s Expensive_Result:%s',
                  limit,
                  current,
                  expensive_function())
    current += 1

I put expensive_function() at the end of the conditional because it is expensive. How can I cache the value to not reiterate over it when logging?

I have considered breaking up the conditional into two, but I am worried it's making the code less readable:

if limit > current:
    expensive_result = expensive_function()
    if expensive_result is not None:
         logging.debug('Limit:%s Current:%s Expensive_Result:%s',
                       limit,
                       current,
                       expensive_result)
         current += 1
Bamcclur
  • 1,949
  • 2
  • 15
  • 19
  • The first thing you should consider is whether `expensive_function` is really so very expensive to be worth the added complexity. Another fairly clean option is to make a memoized version of `expensive_function` as outline here http://www.python-course.eu/python3_memoization.php, for instance (you probably don't need to go as far as making it a decorator for one-off use) – pvg Jun 10 '16 at 01:00
  • 2
    I don't think there's any better way to avoid calling `expensive_function` twice than what you have in your second code block. – Blckknght Jun 10 '16 at 01:05
  • @pvg Unfortunately, I didn't think to put that this is also python 2.7, and apparently memoization doesn't come with that by default. http://stackoverflow.com/questions/11815873/memoization-library-for-python-2-7 – Bamcclur Jun 10 '16 at 01:09
  • @Bamcclur you don't need the decorator, just the return-a-closure thing will work fine in python2.7 – pvg Jun 10 '16 at 01:11
  • Or if you find it too funky, just make it a class and use an ivar to hold onto the result. so then you'd just have instance.check_expensive_result(); anytime you want a full recalc, make a new instance. – pvg Jun 10 '16 at 01:13
  • Ah okay, so would implementing expensive functions with memoization be a good practice to keep doing to keep things fast? – Bamcclur Jun 10 '16 at 01:23
  • 2
    Your second block looks perfectly readable to me. – Bi Rico Jun 10 '16 at 01:24
  • @Bamcclur it really depends how expensive and how often you need to memoize. The implementation with the check that you have now is perfectly reasonable too, as other have said. You can make it even simpler by removing the None check since, stylistically, log level 'debug' is for logging just about everything that happens. Long story short, don't overthink this and worry about performance after you've got things working and done some profiling. – pvg Jun 10 '16 at 02:10

0 Answers0