1

My code is :

  class Handler():

        # make it static
        from pymongo import MongoClient
        client = MongoClient("localhost", 27017)
        db = client.newsdb
        news = db.news

I want to make the client variable to be static, so is above code the correct way to do that ? I also want to use singleton pattern, because maybe the MongoClient is very large element, and I want to new() this element when I really need it....

How can I do that in python ? As a beginner, maybe ask some stupid question, sorry for that in advance...

Matteo Ragni
  • 2,611
  • 1
  • 16
  • 29
liuzhidong
  • 518
  • 3
  • 15

1 Answers1

4

Simplest way to use singleton pattern in Python it's move all code to separate module and import it:

singleton.py:

    from pymongo import MongoClient
    client = MongoClient("localhost", 27017)
    db = client.newsdb
    news = db.news

and use it in other modules:

import singleton
print(singleton.news)
Nikolai Golub
  • 2,799
  • 4
  • 25
  • 56