This maybe a noOb question.
Is it okay to have a global instance defined as such:
# testing.py
class Test(object):
def do_something(self):
etc....
test = Test()
...so that I can just import "test" (ie: from testing import test) and use it. ie:
test.do_something()
...without having to instantiate it every-time in the views every time a request is made. ie:
def MyView(View):
def get(self , request, *args, **kwargs):
test = Test()
test.do_something()
return HttpResponse('testing')
I also do not want to have it in a base handler either (by calling self.test.do_something()), I want to make it completely accessible by just "test" for any request made, in any view, in any module etc...
I want to have simply:
def MyView(View):
def get(self , request, *args, **kwargs):
test.do_something()
return HttpResponse('testing')
Is this the best approach for this kind of scenario? Thanks for any suggestions.
It depends on whether your object is storing state. If so, you should realize that that state will persist across requests. That may be OK, if what it's storing is something generic like a database connection. But if it's in any way related to the request or the user, you will get data leakage across requests, which is a very bad thing.
On the other hand, if you're not storing state, you probably don't want this to be a class anyway: just make do_something a standalone function and import that wherever you need it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With