'How to import global variable from another file?

I have 2 .pys as below. What I want to do is, when I call dictionary() function, it will fill the "global" dictionary my_dict in my test and when I print(keys_list) I want to see the dictionary as a list. If I do it like that, I get NameError: global name 'keys_list' is not defined.

  1. functions.py

    def dictionary():
        global my_dict
        global keys_list
        my_dict = {}
        for i in range(3):
            my_dict.__setitem__(str(i),i)
        keys_list = list(keys)
    
  2. test1.py

    from functions import dictionary
    
    my_dict()
    print(keys_list)
    print(keys)
    

If I define my function in a class as shown below, I get ImportError: cannot import name dictionary.

class functions:
   def dictionary(self):
       global my_dict
       global keys_list
       my_dict = {}
       for i in range(3):
           my_dict.__setitem__(str(i),i)
       keys_list = list(keys)

P.S. The tool is using Python 2.7 (I am trying to write a script for that tool).



Solution 1:[1]

Honestly not 100% sure what you are trying to accomplish. But to be able to use another python function from another file, you'll want to something like this:

The file names file1.py and file2.py so that is why in my import statement I reference file1.

File1.py

class functions:
    my_dict = {}
    keys_list = []
    def dictionary(self):
        for i in range(3):
            self.my_dict.__setitem__(str(i),i)
            self.keys_list.append(str(i))

file2.py

from file1 import functions
tmp = functions()
tmp.dictionary()
print("Keys: " + str(tmp.keys_list))
print("Dictionary: " + str(tmp.my_dict))

Alternative solution global keywords:

File1.py

def dictionary():
    global my_dict 
    my_dict= {}
    global keys_list 
    keys_list = []
    for i in range(3):
        my_dict.__setitem__(str(i),i)
        keys_list.append(str(i))

file2.py

import tmp1

tmp1.dictionary()

print("Keys:" + str(tmp1.keys_list))
print("Dictionary: " + str(tmp1.my_dict))

Output: enter image description here

Hope this helps (I can elaborate if you'd like as well)!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1