To initialize some variables in a Python program (in a structured way, without using OOP), I want to use a function called initialization() , which is called from a main() function . The problem is the scope of these variables, since if I give them their initial value in the initialization() function , trying to use them in the main() function will generate an error because they do not exist there. For example:
import serial
def inicializacion():
puerto = '/dev/ttyACM0'
baudRate = 115200
buffer = ''
ser = serial.Serial(puerto, baudRate, timeout=1)
def main():
inicializacion()
buffer = buffer + leerDatos(ser)
What alternatives are there to avoid using "global" in the initialization function? Is it possible to implement any solution without having to pass the variables as arguments and without having to return them on the "return"?
Well, I don't think this is possible without resorting to the non-recommended haute mantein
global
. The specific case you show applies perfectly in Object Oriented Programming, it would be good if you explain the reason why you are trying to avoid it:If you are trying to use the configuration parameters, you could create a specific file which will be imported on demand:
settings.py
main.py
Another option is the one mentioned by @Carlangueitor in which you move your configuration to a file
.env
within your project and thus avoid exposing the configuration in one of the files. You can use dotenv .I think you could use a dictionary. You can pass the dictionary as well as return it, keeping the changes you make inside it. Take a look at the following code.
You have the code here: http://ideone.com/BjQyuX I hope you find it useful.
The simplest and pythonic way, adapting your own code:
The ideal would be to change the name of
inicializacion
to a more expressive and explicit name, such as:inicializacion_puerto_serie
By passing the values to the function
inicializacion
as default parameters, you can reuse the code with another orbaud_rate
different port.Never forget when you open a file or a serial port (which for the system is the same) to close it correctly to avoid memory leaks.
I propose the following: