python global name 'collections' is not defined even I imported collections

Catherine picture Catherine · Jan 19, 2015 · Viewed 19.8k times · Source

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')

Answer

Malik Brahimi picture Malik Brahimi · Jan 19, 2015

Change from collections import OrderedDict to import collections.