Lazy evaluation in Python

后端 未结 3 1757
醉话见心
醉话见心 2020-11-28 05:44

What is lazy evaluation in Python?

One website said :

In Python 3.x the range() function returns a special range object which computes elements

3条回答
  •  清歌不尽
    2020-11-28 05:58

    A github repo named python patterns and wikipedia tell us what lazy evaluation is.

    Delays the eval of an expr until its value is needed and avoids repeated evals.

    range in python3 is not a complete lazy evaluation, because it doesn't avoid repeated eval.

    A more classic example for lazy evaluation is cached_property:

    import functools
    
    class cached_property(object):
        def __init__(self, function):
            self.function = function
            functools.update_wrapper(self, function)
    
        def __get__(self, obj, type_):
            if obj is None:
                return self
            val = self.function(obj)
            obj.__dict__[self.function.__name__] = val
            return val
    

    The cached_property(a.k.a lazy_property) is a decorator which convert a func into a lazy evaluation property. The first time property accessed, the func is called to get result and then the value is used the next time you access the property.

    eg:

    class LogHandler:
        def __init__(self, file_path):
            self.file_path = file_path
    
        @cached_property
        def load_log_file(self):
            with open(self.file_path) as f:
                # the file is to big that I have to cost 2s to read all file
                return f.read()
    
    log_handler = LogHandler('./sys.log')
    # only the first time call will cost 2s.
    print(log_handler.load_log_file)
    # return value is cached to the log_handler obj.
    print(log_handler.load_log_file)
    

    To use a proper word, a python generator object like range are more like designed through call_by_need pattern, rather than lazy evaluation

提交回复
热议问题