pythonvariablesmoduleassign

Assign and access variable value from another module in Python


I have two modules "main" and "utils". In "utils" I have 2 variables to be global "cod_user" and "name_user". In the "main" module I imported the 2 variables, it has two classes "A" and "B". In class "A" I need to assign value to "cod_user" and "name_user" from the utils module and in class "B" I need to retrieve the value assigned by class "A", but when I access the value it is empty.

My code

utils.py #MODULE

cod_user = ...
name_user = ...
main.py #MODULE

from util import cod_user, name_user

class A():
    def __init__(self) -> None:
        self.assign_values(1, 'User test')
        

    def assign_values(self, cod, name):
        #SET VALUES
        cod_user = cod
        name_user = name
        print(cod_user, name_user)



class B():
    def __init__(self) -> None:
        self.get_values()

    def get_values(self):
        #GET VALUES
        cod = cod_user  
        name = name_user
        print(cod, name) #ERROR VALUES EMPTY


if __name__ == '__main__':
    ca = A()
    cb = B()

       

Solution

  • You can achieve the desired functionality by defining the variables in a separate class to hold the shared data. Here is an example

    class Utils:
        cod_user = None
        name_user = None
    

    Import the util module in another class and use the variables like:

    from util import Utils
    class A():
        def __init__(self) -> None:
            self.assign_values(1, 'User test')
            
    
        def assign_values(self, cod, name):
            #SET VALUES
            Utils.cod_user = cod # changes here
            Utils.name_user = name # changes here
            print(Utils.cod_user, Utils.name_user)
    

    You can apply the same logic in other classes. You can also use the global keyword to access the global variables locally. But, using global variables can make it more difficult to manage and track changes to the variable's value, especially in larger programs with multiple modules and classes