Home > Net >  Access variables from main program in python
Access variables from main program in python

Time:11-08

I'm new to this website, may I have some help on the following?

I have a main.py program that contains the dictionary loaddict.

I have a module outside of the main program that contains multiple functions which all of them requires the dictionary loaddict from the main program.

Is there a way to access the dictionary loaddict from multiple functions in this module without setting loaddict as a parameter for all of them?

The following code doesn't work, as the remaining function still does not have access to loaddict from the function dgm even with the use of keyword global.

## main program (main.py)
## user inputs data into dictionary: loaddict = {some data}

import BeamDiagram.dgm(loaddict, other parameters)
   
## module (BeamDiagram.py)

def dgm(loaddict, other parameters): 
    global loaddict 
    ## some calculations, this part is fine

def function1(some parameters): 
    ## calculations that requires loaddict

def function2(some parameters): 
    ## calculations that requires loaddict

def function3(some parameters): 
    ## calculations that requires loaddict

CodePudding user response:

Your mistake

In my opinion your mistake is only the import instruction, so in your code it is necessary only a correct import:

from main import loaddict

Below I show you the 2 files that I have created in my system (both file are in the same folder /home/frank/stackoverflow).

main.py

loaddict = {'key1': 'value1'}

''' The function print the value of 'key1' 
'''
def print_dict():
    print(loaddict['key1'])

In main.py I have created the function print_dict() which is imported by the script BeamDiagram.py as it is imported the dictionary loaddict (see below for the code of BeamDiagram.py)

BeamDiagram.py

'''
Module BeamDiagram.py
'''

from main import loaddict, print_dict

''' In the function the parametr 'loaddict' has been removed...
'''
def dgm(other_parameters):
    # no global keyword inside the function
    print(loaddict['key1'])

''' The function modify loaddict value and call a function from main.py
'''
def function1(some_parameters):
    # the following instruction is able to modify the value of 'key1'
    loaddict['key1'] = 'value2'
    print_dict()    # print 'value2' on standard output

dgm('other_params')
function1('some_params')

The script BeamDiagram.py calls the functions dgm() and function1() and this means that:

  • it is possible the read access to loaddict (dgm())
  • it is possible the write access to loaddict (function1())
  • the modification of key1 value is visible in main.py, in fact print_dict1() prints value2 which is the value of key1 after that function1() has made the write access to loaddict

Useful link is Python Module Variables.

  • Related