Hi,
I read a blog entry by GVR on interfaces in which he mentioned that you
had to be able to state the type signature of, say, a function.

That got me thinking along the lines of:
  If you have some typical data, then transform it into a string
showing
  its sub-types.
  Could not a regular expression matching this string be used to check
the type signature of the data?

for example:
  >>> data = [[{'a': 1, ('b',):3.0 }, ()]]
  >>> stringrep = typeExpand(data)
  >>> stringrep
  'list<list<dict<string:int,tuple<string>:float>,tuple<>>>'
  >>> re.match(r"^list<list<(dict<.*>|tuple<.*>)*>>$",stringrep)
  <_sre.SRE_Match object at 0x01611F60>
  >>>

Looking at the example above, I don't think regular expression matching
is right.
Some extra syntax such as:
  typeMatcher.match(r"list<list<(dict<.*>|tuple<.*>)*>>", stringrep
Where this matcher is more like a parser and so does '<' '>' nested
bracket matching; changes . to mean 0 or more types (e.g: 'str'; or
'str,str...'); and allows you the shorthand of writing 'list' for
.list<.*>'.

I've done some work below on typeExpand, but I'm not fluent in a parser
module to implement typeMatcher.match quickly.

Enjoy!


#============== BEGIN typeMatcher.py ==================
'''
Object type Expander
'''

import types
from pprint import pprint as pp

# Map types to a type name
type2name = dict( [ (typ,name[:name.rindex('Type')].lower())
                    for name,typ in types.__dict__.iteritems()
                      if type(typ)==types.TypeType
                      and str(typ).find('<type ')>=0 ]
                  +[(type(set()), 'set')] )
#pp(type2name)

def typeExpand(obj):
  ' Expand an objects type'
  ty = type(obj)
  name = type2name.get(ty,'')
  if not name:
    # Make up a name. So "<type 'XX'>" becomes "_type_XX_"
    name = str(type(obj))
    name = name.replace(' ','_')
    name = name.replace('<','_')
    name = name.replace('>','_')
    name = name.replace("'",'')
  typeExpansionHandler = globals().get( name+'__TypeHandler', None)
  if typeExpansionHandler:
    return ''.join([name, '<', typeExpansionHandler(obj), '>'])
  else:
    return name

def list__TypeHandler(obj):
  ' How to expand the contents of a list/tuple'
  return ','.join([ typeExpand(ob) for ob in obj])
tuple__TypeHandler = list__TypeHandler

def dict__TypeHandler(obj):
  ' How to expand the contents of a dict'
  return ','.join([ '%s:%s' % (typeExpand(name), typeExpand(value))
                    for name,value in obj.iteritems()])

def match(matchExprString, typeString): pass

#============== END typeMatcher.py ==================

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to