Home Is there better way to create lazy variable initialization?
 I want to create code that initialize variable only when I really need it. But initializing in the regular way: var = None if var is None: var = factory() var2 = var  Make too much noise in the code. I tried to create fast solution but I feel there is better option. This is my solution that is fast but can't get parameters and use defaultdict for this. def lazy_variable(factory): data = defaultdict(factory) return lambda: data[''] var = lazy_variable(a_factory) var2 = var()  More questions: is there fast python container that holds only one variable? is there a way to return value without calling the function with parenthesis? EDIT: Please consider performance. I know i can create a class that can have this behavior, but it slower then the simple solution and also the default dict solution. trying some of the solutions: define: import cachetools.func import random @cachetools.func.lru_cache(None) def factory(i): return random.random()  and run: %%timeit for i in xrange(100): q = factory(i) q = factory(i)  got: 100 loops, best of 3: 2.63 ms per loop  naive: %%timeit for i in xrange(100): a = None if a is None: a = random.random() q = a q = a  got: The slowest run took 4.71 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 14.8 µs per loop  I'm not sure what was cached defaultdict solution: %%timeit for i in xrange(100): a = lazy_variable(random.random) q = a() q = a()  got: The slowest run took 4.11 times longer than the fastest. This could mean that an intermediate result is being cached. 10000 loops, best of 3: 76.3 µs per loop  Tnx!