global variables

Michael Chermside mcherm at destiny.com
Mon Jul 22 16:47:29 EDT 2002


> Hi!
> I 'm completely new to python. So here's my problem:
> How can I handle global data in my application?
> The application is a database application and I want
> to provide non-static informations, like the user id, name,
> etc. so that every object can access this information.
> Normally, I use C/C++ for coding, but these tricks don't
> work ;-)
> Maybe, you can give me some hints...
> 
> Thanks in advance
> 
> Thorsten Harms


Well, there is certainly more than one way to solve your problem. But 
I'm going to take a while guess and suggest that perhaps the solution 
you are looking for is... Global Variables.

Ok, it's probably not how I would do it, but your subject line gave it away.

Python has global variables... any variable declared at the "top level" 
(ie, not inside a function or class) is a global variable. The only 
trick that you need to know is this: global variables are tracked on a 
per-module basis. This means that if your code is all in one module, 
then you can go ahead and just use globals.

If your code is in more than one module, then a simple solution would be 
to have a module which exists just to store the global variables. You 
could then import this in all of the other modules and access the 
information like this:

     myGlobals.userId

Hope that answers your question.

(PS: You might want to consider other solutions. In fact, I think that 
in this particular case, it is probably NOT wise to use globals... what 
if one day you want to support (for example) multiple users at once? 
What I would suggest is that you create a "Connection" class, with 
userId, name, port, etc as instance variables. But hey... Python is 
flexible... code it the way you are familiar with for now (but plan to 
learn Python idioms later).)







More information about the Python-list mailing list