class db:
global_ids = {}
global_mappings = {}
def __init__:
db_client = sth sth #clinet to mongo db
db_connection = sth sth #connection to mongo db
db_coll = sth sth
I need some class variables (global ids
and global mappings
) that can be initialized only once for class db
and all other instances of db
class can use it.
Value of class variables has to be calculated using by some function which looks up into database. How can I structure my class?
You can think of this as having a memoized class property.
While classproperty is not a python builtin, it is easy to implement:
This can be used like:
What's left now is memoizing it, so the decorated function only gets called once, and future calls return the value computed the first time. This can be done by "injecting" the value into
A.__dict__
, which causes future calls to access it directly, instead of the classproperty: