Importing module of data dicts and constants

Fuzzyman fuzzyman at gmail.com
Sat Nov 25 09:29:03 EST 2006


Nathan Harmston wrote:
> 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


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




More information about the Python-list mailing list