Python 2.6 Global Variables

M

mattofak

Hi All;

I'm new to Python and moving from C, which is probably a big source of
my confusion. I'm struggling with something right now though and I
hope you all can help.

I have a global configuration that I would like all my classes and
modules to be able to access. What is the correct way to do this?

Thanks;
Matthew Walker
 
R

Ronn Ross

Inside the method that you want to use the var prefix the first
instance with global. For example: global my_var. Then you can use the
var like normal in the method. Good luck
 
C

Chris Rebert

Inside the method that you want to use the var prefix the first instance
with global. For example: global my_var. Then you can use the var like
normal in the method. Good luck

Note that without a global declaration, functions can still read
global variables and modify the objects associated with them, but will
be unable to re-bind (i.e. reassign) entirely different objects to
global variables; the `global` statement just permits them to rebind
global variables to new values.

Cheers,
Chris
 
B

Benjamin Kaplan

Hi All;

I'm new to Python and moving from C, which is probably a big source of
my confusion. I'm struggling with something right now though and I
hope you all can help.

I have a global configuration that I would like all my classes and
modules to be able to access. What is the correct way to do this?

Make a separate module with all the config stuff in it, and import
that module everywhere you need it. Just make sure you do "import
settings" and not "from settings import *". The behavior is different.
In the first case, one instance of the module is shared among every
module that imports it, so any changes you make will appear in all
modules. IN the second case, the current values in settings.py are
copied into the local namespace. Changes made in one module won't
appear in the other modules.
 
B

Bruno Desthuilliers

Ronn Ross a écrit :
(please don't top-post - fixed)
> Inside the method that you want to use the var prefix the first
> instance with global. For example: global my_var. Then you can use the
> var like normal in the method. Good luck


Wrong, and wrong again.

1/ you don't have to use the "global" statement to access a "global"
name - only if you plan on rebinding it (which is more often than not a
bad idea but that's another problem)

2/ in Python, "global" really means "module-level" - there's nothing
like a "true" global namespace.
 
C

Chris Rebert

Dear all

How do I write a code that gets executed 'every x' minutes?



I know how to do it 'after x' minutes, I do the following:

def doAtTimerFire():
       """ The things I want to do 'after x' minutes go here. """

And then from main code, I do this:

tmr = threading.Timer(timeInSeconds, doAtTimerFire)
tmr.start()



Please help.

Regards,
Ashish Vyas

Please exercise some basic mailinglist etiquette and start a new
thread, don't hijack an existing one with a completely unrelated
question.
New threads are started by emailing your post to
(e-mail address removed) rather than replying to a message on an
existing topic.

Regards,
Chris
 
A

AK Eric

2/ in Python, "global" really means "module-level" - there's nothing
like a "true" global namespace.

Isn't that __main__?


import __main__
__main__.foo = "asdfasdf"

print foo
# asdfasdf

Not advocating, but it does serve the purpose.
 
D

Dave Angel

AK said:
Isn't that __main__?


import __main__
__main__.foo = "asdfasdf"

print foo
# asdfasdf

Not advocating, but it does serve the purpose.
Good that you're not advocating it, because IMHO it's bad practice to
have circular import dependencies. By using the __main__ alias, you
avoid the worst problems, but that just means the others are more subtle.

You can make it safe, by carefully avoiding certain constructs. But
it's still fragile, in that a minor change in one module of the loop can
cause either an exception or unexpected behavior.

DaveA
 
A

AK Eric

Good that you're not advocating it, because IMHO it's bad practice to
have circular import dependencies.  By using the __main__ alias, you
avoid the worst problems, but that just means the others are more subtle.

I figured I'd get that kind of response, not that it's incorrect ;)
Great power\great responsibility\etc.

As I understand it, when you enter Python statements at the
interactive prompt, it's adding the result directly to ___main___
(which for lack of a better term I like to call 'universal' scope...
rolls off the tongue better than 'doubleunderscore main
doubleunderscore'):
23

While this might not be the most common way of working for most people
(I'm guessing most folks are in a nice cozy IDE), people working this
way are mucking about in the 'universal' scope without (possibly) even
knowing it.
 
B

Benjamin Kaplan

I figured I'd get that kind of response, not that it's incorrect ;)
Great power\great responsibility\etc.

As I understand it, when you enter Python statements at the
interactive prompt, it's adding the result directly to ___main___
(which for lack of a better term I like to call 'universal' scope...
rolls off the tongue better than 'doubleunderscore main
doubleunderscore'):

23

While this might not be the most common way of working for most people
(I'm guessing most folks are in a nice cozy IDE), people working this
way are mucking about in the 'universal' scope without (possibly) even
knowing it.
--

Or, you could use any other random module for this like, say, a module
made specifically for this purpose and given a name like "config.py"
or "settings.py" or something like that which describes what you're
using it for. You don't have a "universal" scope- it's the
module-level scope of the script that is actually run (or the
interactive interpreter in this case).
 
S

Steven D'Aprano

Isn't that __main__?

Well there you go, I just learned something new.

I was going to say "No, every module has its own __main__", and say that
the only truly global namespace was builtins, which you really shouldn't
mess with. But then I decided to just try it, and blow me down, it works!


[steve@sylar ~]$ cat set_parrot.py
import __main__
__main__.parrot = "Norwegian Blue"

[steve@sylar ~]$ cat get_parrot.py
import __main__
print __main__.parrot

[steve@sylar ~]$ python
Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.Norwegian Blue


I'm sure there are all sorts of odd problems this would lead to in large
scale code, but it's a neat trick to know.
 
G

Gabriel Genellina

En Fri, 30 Oct 2009 00:29:27 -0300, Steven D'Aprano
Isn't that __main__?

Well there you go, I just learned something new.

I was going to say "No, every module has its own __main__", and say that
the only truly global namespace was builtins, which you really shouldn't
mess with. But then I decided to just try it, and blow me down, it works!

[steve@sylar ~]$ cat set_parrot.py
import __main__
__main__.parrot = "Norwegian Blue"

[steve@sylar ~]$ cat get_parrot.py
import __main__
print __main__.parrot

[steve@sylar ~]$ python
Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.Norwegian Blue


I'm sure there are all sorts of odd problems this would lead to in large
scale code, but it's a neat trick to know.

It isn't a neat trick anymore once you realize the name '__main__' isn't
special.

Replace __main__ with foo, or config, or whatever, and you get the same
results. Ok, there is a catch: a file with that name must exist, at least
an empty one...

You're just importing the same module from two places; changes done in one
place are reflected in the second place, like with any other object.
 
B

Bruno Desthuilliers

AK Eric a écrit :
Isn't that __main__?
Nope


import __main__
__main__.foo = "asdfasdf"

print foo
# asdfasdf

Not advocating, but it does serve the purpose.

This won't make 'foo' available to other imported modules. Still a
module-level name, and still no "true" global namespace - which FWIW is
a VeryGoodThing(tm).
 
B

Bruno Desthuilliers

Bruno Desthuilliers a écrit :
AK Eric a écrit :

This won't make 'foo' available to other imported modules.

Err, reading Steven and Gabriel's posts, it looks like I'm wrong and
your right. Duh :(

You really shouldn't show this to childrens.
 
D

Dave Angel

Gabriel said:
<div class="moz-text-flowed" style="font-family: -moz-fixed">En Fri,
30 Oct 2009 00:29:27 -0300, Steven D'Aprano

It isn't a neat trick anymore once you realize the name '__main__'
isn't special.

Replace __main__ with foo, or config, or whatever, and you get the
same results. Ok, there is a catch: a file with that name must exist,
at least an empty one...

You're just importing the same module from two places; changes done in
one place are reflected in the second place, like with any other object.
Thanks for saying that.

There are two interrelated advantages to using a separate module for the
purpose.
1) it avoids circular dependency
2) it makes it clear who gets to initialize these "globals"; if this
module doesn't import anything else (other than stdlib stuff), it'll run
to completion before anyone who tries to use these values. So it can
give them all their initial value, and avoid anyone else needing to do
any "existence check" nonsense.

When I've done it, I've called the module globals.py, or flags.py
depending on the primary intent.

DaveA
 
A

AK Eric

It isn't a neat trick anymore once you realize the name '__main__'
True. I do feel a bit less special now :p And again, I think there
is a difference from saying you *can* work a certain way, and you
*should* work a certain way. Making a 'global module' you import and
muck with = good. Other ways discussed = bad (for the most part).
But I think it's important to understand the underlying system
especially when one is first learning: I hand a heck of a time having
someone explain this stuff to me when I was learning the basics (and
I'm still figuring it out, even from this thread) and now that I get
how it works (I uh... think) it makes me a stronger scripter. The
common thought seemed to be "you shouldn't do it that way, so I'm not
going to explain it to you" which I've always found quite
frustrating. And along those lines...

Should we start talking about how you can add stuff to __builtin__ and
then it really is exposed to everything? (right, unless I'm missing
some other Python idiom?) Again, *not advocating* in standard
practice, but I think it's important to understand how it works.
(ducks incoming flak)

#---------------------
# moduleA.py
import __builtin__
__builtin__.spam = 42
__builtins__["ham"] = 24

#---------------------
# moduleB.py
# This will fail if moduleA isn't executed first
print spam, ham
42 24
 
A

Aahz

Isn't that __main__?

import __main__
__main__.foo = "asdfasdf"

print foo
# asdfasdf

Actually, you're almost right, but it's an even WORSE idea than you
thought:

import __builtin__
__builtin__.foo = 'bar'

Kids, do *NOT* do this at home! The reasons why are left as an exercise
for the reader. ;-)
--
Aahz ([email protected]) <*> http://www.pythoncraft.com/

"You could make Eskimos emigrate to the Sahara by vigorously arguing --
at hundreds of screens' length -- for the wonder, beauty, and utility of
snow." --PNH to rb in r.a.sf.f
 
F

Fabio Zadrozny

Hi All;

I'm new to Python and moving from C, which is probably a big source of
my confusion. I'm struggling with something right now though and I
hope you all can help.

I have a global configuration that I would like all my classes and
modules to be able to access. What is the correct way to do this?

Thanks;
Matthew Walker


I'd usually use the singleton pattern in this case (or you can just
create a class and put things in the class -- and just as a note, I'd
try to avoid declaring anything as global unless really needed).

Cheers,

Fabio
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top