How to set instance variable only when first called upon

I'm working with Python/Sage, and running into some performance issues. Suppose I want to set up an instance variable as follows:

class MyClass:
    def __init__(self):
        self.x1 = factorial(10^7)

Now, obviously, my computer is going to take a bit of time to calculate that factorial. I'd rather it not run that computation every time I construct an instance, and only do it when I call upon that particular variable. One solution I've come across is this:

class MyClass:
    def x2(self):
        try:
            return self.x1
        except AttributeError:
            self.x1 = factorial(10^7)
            return self.x1

But this just seems so messy, and requires more variable/method names. Is there some way to say to Python, "Hey, look, I need you to set this instance variable, but can you wait until I actually need it first?" I'm only using factorial(10^7) as an example.

Posted Sep 4, 2014, 2:46 AM UTC

1114
[deleted]•

[deleted]

8
SymplecticOP•

This is exactly what I need. Thank you so much!

Edit: Oh dang, I didn't know that about sage. That cache method would have been ideal. Thank you, though.

2
stubborn_d0nkeyand some 3•

http://ideone.com/Hyy3TJ

That's my shitty replication. It's missing the ability to use any number of arguments, sorry I'm currently on mobile, if you need that and cant figure out how by yourself let me know and I'll get to adding that when I can (warning: dict keys have to be hashable)

2
Samus_git2samus•

how about this?

def MyClass:
    def __init__(self):
        self._x1 = None

    @property
    def x1(self):
        if self._x1 is None:
            self._x1 = factorial(10^7)
        return self._x1
2
indosauros•

If you are using Python 3.2+, you can decorate your second example with @property and @functools.lru_cache

import functools

class MyClass:
    @property
    @functools.lru_cache()
    def x1(self):
        return factorial(10^7)

@property allows you to access x1() as a property, e.g.

>>> c = MyClass
>>> c.x1
6227020800

And @functools.lru_cache acts as memoization, which is what your second example is doing, i.e. calculating the result the first time and storing it so it isn't calculated in subsequent runs

If you are using Python 3.1 or lower, you have to use a backport of lru_cache (or just write your own memoizer, as in your second example). Convention is to use _func for the stored value, so _x1 stores the memoized value for x1()

5
kalgynirae3.4 and 2.7•

Doesn't decorating x1 with lru_cache still result in a call to factorial for each instance? I think OP should decorate factorial (instead of x1) with lru_cache.

4
indosauros•

You're right, the class-level cache from the other answer solves it as well of you want caching across instances (if you dont control factorial)

2
SymplecticOP•

That @property looks like it will help clean things up. Thank you.

1
hharisonhsharrison•

A good answer here involves @property and @functools.lru_cache (or some other memoization), as others have pointed out. I thought I'd point out the typical convention in Python for dealing with this issue of "too many names". Because there are legitimate reasons to want to have two versions of an attribute like you have x1 and x2. What you would do is name the real attribute with an underscore (e.g. _x) and the one you actually want callers to use, without (e.g., x).

The naive way I would do it that's similar to the logic you used but a bit better (since another convention is to always define all your attributes in __init__):

class MyClass:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        if self._x is None:
            self._x = factorial(10^7)
        return self._x

(Just noticed u/Samus_ posted almost the same code. Oh well I'm posting anyway)

4
SymplecticOP•

My background is in mathematics rather than programming, so my code is generally lacking in these kinds of conventions (and looks super messy as a result!). Hence, I do appreciate hearing about them. I'll update my code now. Thank you.

1
xiongchiamiovxiongchiamiov•

If you're writing your own memoizer, here's a better way:

def foo(self):
    if not self.baz:
        self.baz = spam()

    return self.baz

Writing this on my phone, so excuse any mistakes, but that's the general pattern. I feel that's cleaner than the try-except method you have written.

2
ewiethoffproceedest on to 3•
>>> 10^7
13
>>> 10**7
10000000
2
SymplecticOP•

I'm not sure I follow? Is this a difference between working with Sage, and working just with Python?

sage: 10^7
10000000
2
ewiethoffproceedest on to 3•

Ah! I'm not familiar with Sage. In plain-vanilla Python, ^ is the "bit-wise exclusive or" operator, and ** is for exponentiation.

2
SymplecticOP•

This is good to know, in case I ever switch from Sage to Python + a few modules. Thank you!

2