Referencing Variables in Python Imported Functions

Asked

Viewed 1,279 times

1

I am learning Python on my own and in many videos and subjects programmers advise and emphasize the importance of "clean and organized codes". So I’m trying to create classes and functions in separate files to then import them and use them in a main file, but I find the following problem:

In a separate file (Functions.py for example) I created a function that asks a question and stores it in a global variable:

def Pergunta(X):
   global Resposta
   Resposta = input(X)

Let’s say, now, that I want to print a greeting inside this very file:

def Pergunta(X):
   global Resposta
   Resposta = input(X)

print('Sejam bem-vindos, {}!'.format(Resposta))

Doing this, if the name is "Fulano" the program returns:

'Sejam bem-vindos, Fulano!'

Now my question: if, in another file, I import that same function by adding the variable Resposta = '', as follows:

from Funções import Pergunta

Resposta = ''
Pergunta('Qual é o seu nome?')
print('Sejam bem-vindos, {}'.format(Resposta))

The result is that the program does not recognize the input that I would like to assign (even if I mark the variable as global) and return:

'Sejam bem-vindos, !'

If possible, can anyone explain to me why this happens when I import the function to a new file or how I can get this result correctly?

Thank you for your attention.

  • 3

    Instead of relying on a global variable, I think it makes more sense for the function to simply return the entered value. More or less: https://ideone.com/iHfYok

  • Good evening, hkotsubo, thank you for your attention! So... I saw the file and this approach even works, but my question is whether it works when I import the function to another code/file.py

  • 2

    Yes, it works: https://repl.it/repls/DenseSunnyProprietarysoftware

  • Sorry for the delay. I finally got to sit down to test and this approach actually worked. I appreciate the help! There was doubt about what happens to variables in this case, but I will take some time to study further. Very grateful!

1 answer

3


In Python, the so-called global variables are not truly "global" - fortunately. This makes them manageable.

The model you are trying to make is not the best - but do so, gain some experience and over time you will find more consistent ways.

So - when a variable is declared as global within a module, it becomes a variable of that module. Then it can be accessed by other functions, either in that module or by code in other files, in the same way that you access the functions of the same module: with the operator "." used as attribute access syntax:

import funcoes

def funcao_no_outro_modulo():
    print(funcoes.Pergunta)

    ...
    funcoes.Resposta = "a resposta descoberta nesse outro modulo é X"

If you try to import the variable directly from the module, with code like from funcoes import Pergunta - you will get a reference to the contents of that variable as it was at the time the command import was executed. But for strings and numbers (and other immutable objects), if the variable in the original module takes another value, it will point to another object. And the variable that we have in the module where we imported, will continue related to the initial object.

So in this example:

modulo1.py:

from modulo2 import Estado, mudar_estado

print(Estado)
mudar_estado()
print(Estado)

Modulo2.py:

Estado = "inicial"

def mudar_estado():
    global Estado
    Estado = "intermediário"

If you run module 1, you will see "initial" printed twice. If you rewrite module 1 as:

import modulo2

print(modulo2.Estado)
modulo2.mudar_estado()
print(modulo2.Estado)

will see the change.

It’s easy to see that if you have so few when about 4 or 5 of these variables in different files, the program starts to become unpredictable and ingestible - that’s why I said try and find a cool practice.

A way to go, that gets better, is to keep all the variables that go keep values you want to track from various functions in a single module - type variaveis.py - and then always uses

import variaveis

variaveis.Pergunta = "que dia é hoje?"

When you understand this, just better understand the elements of your problem, replace them as classes instead of modules as functions, and that’s it - instead of global variables you’ll have object attributes, and a program "grown" :-)

  • Thank you very much, jsbueno! I am breaking my face little by little, but learning! I think I understand what is happening. I will try this approach you suggested. I am studying Classes and POO and the next step is to try to think more like this. I appreciate the attention and the explanation!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.