facha
facha

Reputation: 12522

python: variable availability in imported files

I've got a noob python question about variable scope.

I've created two scripts. One is included into other:

file1.py

a = 10
from file2 import *

file2.py

print a

When I try to execute file1.py, I get this error: NameError: name 'a' is not defined

So, this is my question. Is it possible to make script's variables available in the included scripts?

UPDATE: What I'm actually trying to do is something like this: main.py

from config include *
from utils include *

In config.py I'd have

filename = "/tmp/file.txt"

In utils.py I'd have

def write_file():

The problem is that I have a whole bunch of small functions which all need filename. Right now I don't have those function in utils.py. I have them in main.py. But as over time main.py got bigger and bigger I'm thinking about if there is an easy way to move the utility functions away from the main script.

Upvotes: 0

Views: 76

Answers (2)

korefn
korefn

Reputation: 955

From your update it would be in order to assume you want configurations in config.py. The best way to solve your problem would be to send the filename as a parameter to utils.py methods.

def write_file(filename)

is a more useful utility function that

def write_file()

that depends on variable filename to be in scope! IMHO Its also good programming practice(prefer explicit over implicit was it?).

Upvotes: 0

Volatility
Volatility

Reputation: 32310

The print a in the second file executes in that scope, not of the first one. Python modules aren't like C header files, in that the code isn't 'embedded' into the file - the module is loaded, and the code is run, therefore allowing you access to names from that module.

A good demonstration of this is the if __name__ == '__main__': block that is commonly found in modules. If this code was actually embedded into the script, the code inside the block would run every time, as __name__ would always be '__main__'. But because all the code is run inside the scope of the imported module, __name__ would be a different value, so the code would only run if it was in the top-level script.

To be able to print a successfully you would need to from file1 import a in the second file.

Addressing your update, this shouldn't be a problem. from config import filename in the utils script will allow it to use the variable, as long as it is imported before filename is referenced.

Upvotes: 1

Related Questions