Namespaces/introspection: collecting sql strings for validation

Scott David Daniels scott.daniels at acm.org
Sun Apr 22 15:09:52 EDT 2007


Martin Drautzburg wrote:
> I would like to validate sql strings, which are spread all over the
> code, .... The statements will not be assembled from smaller pieces,
> but they will not neccessarily be defined at module level. I could
> live with class level, ....
> parse the source file, but I am willing to mark the strings so it is
> easier to tell sql from non-sql.
> 
> ... Or is there a completely different way to do such a thing?

How about using some variation of:
     class _Dummy: pass
     OLD_STYLE = type(_Dummy)


     def generate_strings(module):
         '''Generate <class> <name> <value> triples for a module'''
         for top_level_name in dir(module):
             top_level_value = getattr(module, top_level_name)
             if isinstance(top_level_value, basestring): # strings
                 yield None, top_level_name, top_level_value
             elif isinstance(top_level_value, type): # new-style class
                 for name in dir(top_level_value):
                     value = getattr(top_level_value, name)
                     if isinstance(value, basestring):
                         yield top_level_name, name, value


     def sometest(somestring):
         '''Your criteria for "is an SQL string and has misspellings".'''
         return len(somestring) > 20 and '


     def investigate(module):
         for modname in sys.argv[1:]:
             for class_, name, text in generate_strings(
                                      __import__(modname)):
                  if remarkable(text):
                      if class_ is None:
                           print 'Look at %s's top-level string %s.' % (
                                        modname, name)
                      else:
                           print "Look at %s, class %s, string %s.' %
                                        modname, class_, name)


     if __name__ == '__main__':
         import sys
         for modname in sys.argv[1: ]:
             investigate(modname, sometest)

-- 
--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list