Importing module of data dicts and constants

N

Nathan Harmston

Hi All,

I ve got a single module which I m using to contain a lot of
dictionaries, constants, general information, which are used by
various other modules. However I can't seem to access them:

in data.py
_SEQTYPE_DNA = 0
_SEQTYPE_RNA = 1
_SEQTYPE_PROT = 2
_seqType = { "DNA":_SEQTYPE_DNA, "RNA":_SEQTYPE_RNA, "PROTEIN":_SEQTYPE_PROT }

but in test.py
from data import *

class Test(object):
def __init__(self, type):
self.type = _seqType[type]
def test(self):
return self.type

t = Test("DNA")
print t.test()

File "test.py", line 24, in __init__
self.type = _seqType[type]
NameError: global name '_seqType' is not defined

I think I m doing something incredibly wrong/stupid here....
Can anyone help?

Many Thanks

Nathan

PS. I was wondering if the use of a data module to store constants and
dictionaries is good design??? or not?
 
F

Fuzzyman

Nathan said:
Hi All,

I ve got a single module which I m using to contain a lot of
dictionaries, constants, general information, which are used by
various other modules. However I can't seem to access them:

in data.py
_SEQTYPE_DNA = 0
_SEQTYPE_RNA = 1
_SEQTYPE_PROT = 2
_seqType = { "DNA":_SEQTYPE_DNA, "RNA":_SEQTYPE_RNA, "PROTEIN":_SEQTYPE_PROT }

but in test.py
from data import *

class Test(object):
def __init__(self, type):
self.type = _seqType[type]
def test(self):
return self.type

t = Test("DNA")
print t.test()

File "test.py", line 24, in __init__
self.type = _seqType[type]
NameError: global name '_seqType' is not defined

I think I m doing something incredibly wrong/stupid here....
Can anyone help?

This looks fine to me. Perhaps when you import from data you are not
getting the module you expect.

How about adding the following lines to your code and seeing if you get
the results you think you should :

import data
print data.__file__

In general it is better to use the following import form. This way you
can explicitly see where your names are coming from :

from data import _seqType

Storing constants in a data module is fine if you don't expect end
users to edit the file. 'import' executes code, so it can be a security
hole to store configuration data in Python modules.

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/weblog/index.shtml
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top