Interface type checking

P

Paddy

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 said:
>>> re.match(r"^list<list<(dict<.*>|tuple<.*>)*>>$",stringrep)
said:

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 ==================
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,056
Members
48,769
Latest member
Clifft

Latest Threads

Top