13 votes

Initialization of variables in Python using a function separate from main ()

To initialize some variables in a program written in Python (in a structured way, without the use of object-oriented programming), I want to use a function called home()which is invoked from a function to main(). The problem is the scope of these variables, because if I give the initial value in the function home(), when you try to use them in the function main() will generate an error because there does not exist. 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 are alternatives to avoid the use of "global" in the initialization function? Is it possible to implement any solution without having to pass the variables as arguments and without having to send them back in the "return"?

12voto

César Points 14430

Well, I don't think this is possible without resorting to highly non-recommended global. The specific case to which samples applies perfectly in the Object-Oriented Programming, it would be good that you explain the reason why you're trying to avoid it:

import serial


class Clase():
    def __init__(self, puerto, baud_rate, buffer) # inicializacion()
        self.puerto = puerto
        self.baud_rate = baud_rate
        self.buffer = buffer
        self.serial = serial.Serial(puerto, baudRate, timeout=1)

    def leer_datos(self):
        # Tu código

If you're trying to use the settings, you could create a specific file which will be imported on demand:

settings.py

puerto = '/dev/ttyACM0'
baudRate = 115200
buffer = ''

main.py

import serial
import settings


def main():
    ser = serial.Serial(settings.puerto, settings.baudRate, timeout=1)
    buffer = settings.buffer + leerDatos(ser)

Another option is the one mentioned by @Carlangueitor in which your settings the move to a file .env within your project and so you avoid exposing the configuration in one of the files. You can use dotenv.

10voto

Baltasarq Points 994

I think you could use a dictionary. You can pass the dictionary, as well as return it, keeping the changes you make inside it. Look at the following code.

 def inicializacion():
    toret = {}
    toret["puerto"] = '/dev/ttyACM0'
    toret["baudRate"] = 115200
    toret["buffer"] = ''

    return toret


def main():
    datos = inicializacion()
    datos["buffer"] = "hola"
    print(datos["buffer"])
    print(datos)

main()
 

You have the code here: http://ideone.com/BjQyuX I hope you find it useful.

4voto

tinproject Points 213

The easiest and most pythonica, adapting your own code:

import serial

def inicializacion(puerto='/dev/ttyACM0', baudRate=115200):
    ser = serial.Serial(puerto, baudRate, timeout=1)
    return ser


def main():
    ser = inicializacion()
    buffer=''
    buffer = buffer + leerDatos(ser)

    # El puerto se ha de cerrar para evitar fugas de memoria..
    ser.close()

The ideal would be to change the name of inicializacion to a more expressive and explicit as, e.g.: inicializacion_puerto_serie

To pass the values to the function inicializacion as default parameters you can reuse the code with another port or another baud_rate different.

Never forget when you open a file or a serial port (that for the system is the same thing) to close it down properly to avoid memory leaks.

3voto

Santi92 Points 1111

I propose the following:

 import serial

puerto='/dev/ttyACM0'
baudRate=115200

def main():
    buffer=''
    serial.Serial(puerto, baudRate, timeout=1)
    buffer=buffer+leerDatos(str)
 

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X