python global name 'collections' is not defined even I imported collections
25,321
Solution 1
Change from collections import OrderedDict
to import collections
.
Solution 2
Option 1: Change
from collections import OrderedDict
to
import collections
option 2:
Change
collections.OrderedDict()
to
OrderedDict()
Solution 3
You don't import collections, you only import from collections. Simply write OrderedDict
instead of collections.OrderedDict
.
Author by
Catherine
Updated on July 21, 2022Comments
-
Catherine almost 2 years
The following is config.py:
from collections import OrderedDict def test_config(fileName): tp_dict = collections.OrderedDict() with open("../../config/" + fileName, 'r') as myfile: file_str = myfile.read().replace(' ', '').split('\n') tp_list = [] for i, x in enumerate(file_str): x = x.strip() try: key = x[:x.index(':')].strip() value = x[x.index(':')+1:] if key == 'testpoint': pass else: tp_dict[key] = value.strip().split(',') except ValueError,e: pass if i % 4 == 0 and i != 0: tp_list.append(tp_dict.copy()) return tp_list
I'm using the function in another file test.py:
import config a = config.test_config('test.txt') NameError: global name 'collections' is not defined
But if I copy paste the whole code from config.py to the top of test.py, and then use the function, then I have no error(See code below). Can anybody explain this to me please? I'm so so so confused. Thank you very much!
""" This is test.py """ from collections import OrderedDict def test_config(fileName): tp_dict = collections.OrderedDict() with open("../../config/" + fileName, 'r') as myfile: file_str = myfile.read().replace(' ', '').split('\n') tp_list = [] for i, x in enumerate(file_str): x = x.strip() try: key = x[:x.index(':')].strip() value = x[x.index(':')+1:] if key == 'testpoint': pass else: tp_dict[key] = value.strip().split(',') except ValueError,e: pass if i % 4 == 0 and i != 0: tp_list.append(tp_dict.copy()) return tp_list a = test_config('test.txt')
-
Catherine over 9 yearsYou're right. But why it doesn't complain an error in the test.py then?