Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing class variables only once

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?

like image 503
Prannoy Mittal Avatar asked Jun 08 '15 18:06

Prannoy Mittal


1 Answers

You can always test if those values have been set first; if you are not using threads that is as simple as:

class db: 
      global_ids = {}
      global_mappings = {}

      def __init__(self):
          self.db_client     = sth sth #clinet to mongo db
          self.db_connection = sth sth #connection to mongo db 
          self.db_coll        = sth sth

          if not db.global_ids:
              # set key-value pairs on db.global_ids

          if not db.global_mappings:
              # set key-value pairs on db.global_mappings

That way you defer setting those class attributes until the first time you create an instance of the class.

You can also opt to set those same values when defining the class, of course.

like image 148
Martijn Pieters Avatar answered Oct 06 '22 16:10

Martijn Pieters