Python : Singleton class object to persist list be

2019-08-28 02:12发布

I want to have dict / list to which I can add values, just like models can be added to the admin register in django !

My attempt : (package -> __init__.py)

# Singleton object

# __init__.py (Package: pack)
class remember:
  a = []
  def add(data):
    a.append[data]

  def get():
    return a

obj = remember()


# models1.py
import pack

pack.obj.add("data")

# models2.py
import pack

pack.obj.add("data2")
print pack.obj.get()   

# We should get: ["data", "data2"] # We get : ["data2"]

How to achieve the desired functionality ?

Some say that methods can do this if you don't need sub-classing, how to do this with methods ?

Update: To be more clear :

Just like django admin register any one can import and register itself with admin, so that register is persisted between imports.

2条回答
▲ chillily
2楼-- · 2019-08-28 02:30

If it's a singleton you're after, have a look at this old blog post. It contains a link to a well documented implementation (here).

查看更多
Viruses.
3楼-- · 2019-08-28 02:54
  1. Don't. If you think you need a global you don't and you should reevaluate how you are approaching the problem because 99% of the time you're doing it wrong.

  2. If you have a really good reason to do it perhaps thread_locals() will really solve the problem you're trying to solve. This allows you to set up thread level global data. Note: This is only slightly better than a true global and should in general be avoided, and it can cause you a lot of headaches.

  3. If you're looking for a cross request "global" then you most likely want to look into storing values in memcached.

查看更多
登录 后发表回答