Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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')
like image 584
Catherine Avatar asked Jan 19 '15 19:01

Catherine


2 Answers

Change from collections import OrderedDict to import collections.

like image 181
Malik Brahimi Avatar answered Oct 13 '22 09:10

Malik Brahimi


Option 1: Change

from collections import OrderedDict

to

import collections

option 2:

Change

collections.OrderedDict()

to

OrderedDict()
like image 41
Vikrant Avatar answered Oct 13 '22 08:10

Vikrant