I have been developing this project for some time, I only had it in a single file and when I modularized it I had problems compiling the type "global name 'file' is not defined", where file is a global variable. I have a file "main" which is the following:
#Laberinto.py
#---------------------------IMPORTACION DE LIBRERIAS------------------------------------
from Clases import Jugador
from Clases import Camino
from Clases import Arbol
from Funciones import cargarArchivo
from Funciones import cargarLaberinto
from Funciones import MazeRunner
#-------------------------FIN IMPORTACION DE LIBRERIAS----------------------
#---------------------------INICIALIZACION DE VARIABLES GLOBALES----------
arbol = Arbol(60,120)
nodoPadre = arbol.listaNodos [0]
ancho = 0
alto = 0
laberinto = []#matriz de 1's y 0's que definen al laberinto
mapaConocido = []
archivo = open( "file/matriz.txt", "r" )#archivo que contiene la informacion del laberinto
listaMuros = []#lista de todos los muros con su posicion
listaCamino = []
listaVisitados = []
#-------------------------FIN INICIALIZACION DE VARIABLES GLOBALES-----------------------------------
def main(ancho,alto):
cargarArchivo(archivo,laberinto,mapaConocido)
alto,ancho = cargarLaberinto(laberinto,listaCamino,listaMuros,ancho,alto)
jugador = Jugador(ancho,alto)
MazeRunner(jugador,listaCamino,listaMuros,listaVisitados,ancho,alto,mapaConocido,arbol,nodoPadre)
main(ancho,alto)
The previous error is passed by passing to each function the global variables that will be used but as some functions send others to call in their procedure, these also pass the variables that will occupy and I get a mess pass as many variables if they are defined in the main file as global (not with the global word but outside any function) and can not modify them from each function without passing them as a parameter. This if the functions did if they were in the same file, but I wanted to make it more modularized. My question is whether there is any way for functions in independent modules to access these global variables without passing them as a parameter or can they only do so while in the same module where the variables were defined?
Here I add the code of another of the modules (loadFile):
#cargarArchivo.py
def cargarArchivo(archivo,laberinto,mapaConocido):#Funcion que lee el archivo txt con la forma del laberinto
for line in archivo.readlines():
fila = list(line)
fila.pop()
while fila.count(',') != 0: #busca y retira las comas en la lista
fila.remove(',')
print fila
laberinto.append( fila )
mapaConocido.append( fila )