Python : Singleton class object to persist list between imports ? (Like django admin register)

一个人想着一个人 提交于 2019-12-11 18:17:02

问题


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.


回答1:


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).




回答2:


  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.



来源:https://stackoverflow.com/questions/8207100/python-singleton-class-object-to-persist-list-between-imports-like-django-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!