[Tutor] importing variable contents, and variable naming problms

Magnus Lycka magnus@thinkware.se
Sun, 01 Sep 2002 08:34:30 +0200


At 12:49 2002-08-31 +1200, Thomi Richards wrote:
>ok, I'll explain.. I have a program, which has a directory under it
>called species/. under this dir the END USER creates some modules, which
>define the species behavior. however, i don't know what they are going
>to call their species, they could call it 'lion', or they could call it
>'blahblahlongname', however, no matter what it is called, i need to
>import it. using os.listdir, i can add the correct directories to the
>sys.path list, but i now need to import the species/lion/lion.py file.
>of course, i don't know that it will be called 'lion.py' before the
>program starts , so i cannot hard code this in.. does that make any
>sense??

Sure.

But you know the contents of each module, right? I.e. what
variables, classes, functions etc it contains?

You have two big problems, name-clashes and incorporating
unpredictable variable names. You don't want any of that.

And what happens if someone would create a species called
sys, os or sockets? I think you need to use some kind of
prefix to your filenames to be certain--even if you avoid
all other name clashes.

Then you place all your modules in a list or dict.

Untested code follows:

import os
directory =3D '/some/path/'
prefix =3D 'species_'
moduleNames =3D [fileName for fileName in os.listdir(directory)
                         if fileName.startswith(prefix)]
speciesModules =3D {}
for modName in moduleNames:
     speciesName =3D modName[len(prefix):]
     exec("import %s as speciesModules[%s]" % (modName, speciesName))

Now you have a dictionary of modules, keyed by animal name.

If they all have the attribute "maxWeight" you can list the
max weights in alphabetical order for the species as:

speciesNames =3D speciesModules.keys()
speciesNames.sort()
print "%15s|%8s" % ('Species', 'Weight')
for name in speciesNames:
     print "%15s|%8i" % (name, speciesModules[name].maxWeight)


--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se