Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion about global variables in python

I'm new to python, so please excuse what is probably a pretty dumb question.

Basically, I have a single global variable, called _debug, which is used to determine whether or not the script should output debugging information. My problem is, I can't set it in a different python script than the one that uses it.

I have two scripts:

one.py:
-------

def my_function():
  if _debug:
    print "debugging!"


two.py:
-------

from one import *
_debug = False

my_function()

Running two.py generates an error:

NameError: global name '_debug' is not defined

Can anyone tell me what I'm doing wrong?

like image 286
Ben Avatar asked Jan 30 '09 12:01

Ben


2 Answers

There are more problems than just the leading underscore I'm afraid.

When you call my_function(), it still won't have your debug variable in its namespace, unless you import it from two.py.

Of course, doing that means you'll end up with cyclic dependencies (one.py -> two.py -> one.py), and you'll get NameErrors unless you refactor where various things are imported and declared.

One solution would be to create a simple third module which defines 'constants' like this, which can be safely imported from anywhere, e.g.:

constants.py
------------
debug = True

one.py
------
from constants import debug
#...

two.py
------
from constants import debug
#...

However, I would recommend just using the built in logging module for this - why not? It's easy to configure, simpler to use, reliable, flexible and extensible.

like image 123
James Brady Avatar answered Oct 14 '22 16:10

James Brady


Names beginning with an underscore aren't imported with

from one import *
like image 21
kgiannakakis Avatar answered Oct 14 '22 14:10

kgiannakakis