[Tutor] advice on global variables
James Reynolds
eire1130 at gmail.com
Wed Jul 11 01:00:49 CEST 2012
Sent from my iPad
On Jul 10, 2012, at 3:11 PM, Chris Hare <chare at labr.net> wrote:
>
> I know they are bad. That is why I would prefer not to use it, but I am not sure how else to handle this problem.
>
> In this app, the user must log in. Once authenticated, they have a userid stored in the SQLite database. Before splitting my app into multiple files, I used a global variable. I know its bad, but it worked. Now that things are split apart, the classes which used it previously now don't see it anymore, even using the global keyword. I think this is the expected behavior. See here
>
> file: a.py
>
> import b
> global_var = "global"
>
> def func1():
> global global_var
> print "global var in func1 = %s" % global_var
>
> class intclass:
> def func2(self):
> global global_var
> print "global var in intclass = %s" % global_var
>
> print "global_var = %s" % global_var
> func1()
> f = intclass()
> f.func2()
> g = b.extclass()
> g.func3()
>
> file: b.py
>
> class extclass:
> def func3(self):
> global global_var
> print "global var in extclass = %s" % global_var
>
> When I run it, I get what I think the expected behavior, that the external class ext class won't be able to see the global_var
>
> Big-Mac:t chare$ python a.py
> global_var = global
> global var in func1 = global
> global var in intclass = global
> Traceback (most recent call last):
> File "a.py", line 18, in <module>
> g.func3()
> File "/Users/chare/Development/python/animaltrax/pkg/t/b.py", line 5, in func3
> print "global var in extclass = %s" % global_var
> NameError: global name 'global_var' is not defined
>
> So - my question is this: how do I solve the problem of multiple classes needing to get access to a value which needs to be preserved across the lifetime of the running application?
>
> One thought was a RAM based SQLite database, but that seems like a lot of work. I dunno, maybe that is the option.
>
> suggestions, ideas, criticisms are all welcome. Python code aside, I just don't know how to approach this problem in Python.
>
> Thanks, as always for the feedback and guidance.
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
I'll admit it's a little tough for me to read your code.
If you need to store some information, store it to your db and access it later.
If would rather have he settings in the source code, study django's conf and how it handles configurations.
Better yet, why not just use django for your app?
More information about the Tutor
mailing list