looking for way to include many times some .py code from anotherpython code

Peter Hansen peter at engcorp.com
Tue Mar 8 17:53:10 EST 2005


Martin MOKREJŠ wrote:
> I need to test almost every for it's content. Some tests
> are just that the value is non-empty (few cases), but in most cases
> a lot more checks (only certain values allowed, or only int type allowed,
> or only \w is allowed ...).

This sounds very much like an opportunity for some code
that is "data-driven".  Rather than dealing with individual
variables, you define data structures (or even just input
files specialized for your situation, if that seems best)
which describe the sorts of tests you talk about above.

You would include the names of the various fields, in
order to match them up with their respective descriptions,
and then have generic code that dealt with each field in
the appropriate manner, driven by what was in the above
data structures.

As trivialized example, to show what I mean:

import types
NonEmpty = object()
Unique = object()

info = {
     'field1': (NonEmpty, r'\w+', types.int),
     'field2': (None, r'[a-zA-Z_][a-za-Z0-9]*', types.str),
     'foo': (Unique, r'\d+', types.float),
     }

# inside some routine that loads the data:
for name, text in readMyData():
     try:
         flag, pattern, type = info[name]
     except KeyError:
         print 'ignoring unrecognized field', name
     else:
         if flag == NonEmpty:
             if text == '':
                 raise ValueError('field %s cannot be empty' % name)
         value = convertToType(text, type)
         storeMyData(name, value)


and so forth....

I think that gives the idea.  Generally if I had
hundreds of fields, I wouldn't even bother with
the hardcoded dict as above but would just define my
own file format to describe all this, and parse it
first into some internal representation before trying
to read the real data.

-Peter



More information about the Python-list mailing list