I have an object that is basically a Python implementation of an Oracle sequence. For a variety of reasons, we have to get the nextval of an Oracle sequence, count up manually when determining primary keys, then update the sequence once the records have been inserted.
So here’s the steps my object does:
- Construct an object, with a
key_generatorattribute initially set to None. - Get the first value from the database, passing it to an itertools.count.
- Return keys from that generator using a property
next_key.
I’m a little bit unsure about where to do step 2. I can think of three possibilities:
- Skip step 1 and do step 2 in the constructor. I find this evil because I tend to dislike doing this kind of initialization in a constructor.
- Make
next_keyget the starting key from the database the first time it is called. I find this evil because properties are typically assumed to be trivial. - Make
next_keyinto aget_next_keymethod. I dislike this because properties just seem more natural here.
Which is the lesser of 3 evils? I’m leaning towards #2, because only the first call to this property will result in a database query.
I think your doubts come from PEP-8:
Adherence to a standard behavior is usually quite a good idea; and this would be a reason to scrap away solution #2.
However, if you feel the interface is better with property than a method, then I would simply document that the first call is more expensive, and go with that (solution #2).
In the end, recommendations are meant to be interpreted.