[Tutor] advice on global variables

Walter Prins wprins at gmail.com
Thu Jul 12 11:16:56 CEST 2012


Hi Chris,

James has already given a response but I can't resist also chiming in,
see below:

On 11 July 2012 15:30, Chris Hare <chare at labr.net> wrote:
> I like where this is going Walter.  I guess where I am confused is this:
>
> the globals are not static - they are set once and then won't change during the lifetime of the user's session.

Whether they change or not is beside the question.  They can get set
once, they can be set multiple times, it really doesn't matter.


> So, after messing around with the ram DB idea, I realized I was back to the same problem.

Exactly. :)

> Let's say I create a dictionary to store all of the "globals" and other data I want available everywhere and I put that in a class.  > Every time I create an instance of the class to be able to access the data,

Now why do you think that you need to instantiate the class everytime
you want to access the same data?  Just damn well create the object
once and use it when you need it.  Do you not know that your own
objects can be treated as a parameters to a methods/functions just
like any other Python object or type?

> a new instance of the dictionary is created that loads the same data in it.  Seems kinda inefficient for me, especially if the data changes in one instance - how do you keep the others all in sync, or does that just happen automatically?

Well exactly.  Just use the same object everywhere!

> I think there is something that I fundamentally not understanding and I don't know what it is.   Am I making this too complicated?

Yes and yes.  I think you are getting confused with and are maybe
conflating the names an object might be associated to (and the
namespaces those names live in), the lifetime of an object might have
(e.g. when is it created, when does it get destroyed.), and where
objects may be access from. A lot might be said about this but suffice
it to say that you should conceptualize objects as staying in
existence until the last reference to them is removed (reference being
either a name label or entry another container object reference such
as a list.)  Secondly, all you need to access an object is a reference
to it -- either a name label or direct reference (e.g. as passed in a
container such as a list.)  The reference may be received as a
parameter to a function or method either directly or indirectly, or
code may fetch it from a suitable module itself by importing the
module.  (Which incidentally is also an object.)

Anyway I don't have time to elaborate more right now but I suggest you
try to read up on these topics a bit yourself first and then
experiment apart from the program you're working on to help cement the
various basic ideas surrounding objects & their lifetimes, references
to objects, passing parameters and so on.  Then come back with more
questions.

Walter


More information about the Tutor mailing list