A Type Coerced Environment for Python
http://littlelanguages.com/web/languages/python-type-coercion/
Here's a fun little language. This only works in python 2.4, and it has problems there (it breaks if you invoke globals). The idea here is that python permits general mappings (as opposed to dictionaries) to be used for the local() namespace (though not the global() namespace). Here we are merely starting an interactive environment using a modified dictionary with an overridden __setitem__, and performing type coercion there.
#!/usr/bin/env python2.4
import code
class TypedDictionary(dict):
def __setitem__(self, key, value):
if self.has_key(key):
t = type(self[key])
if t != type(value):
try:
value = t(value)
except Exception:
raise TypeError, \
"illegal assignment to '%s':" \
" %s cannot be coerced to %s" \
% (key, type(value), t)
dict.__setitem__(self, key, value)
code.interact(local=TypedDictionary())
This simple little environment provides basic (and very incomplete) type coercion to python, as the sample session below shows:
>>> a = 1
>>> type(a)
<type 'int'>
>>> a
1
>>> a = '23'
>>> type(a)
<type 'int'>
>>> a
23
>>> b = '4'
>>> type(b)
<type 'str'>
>>> b
'4'
>>> b = 23
>>> type(b)
<type 'str'>
>>> b
'23'
>>> c = 2.3
>>> type(c)
<type 'float'>
>>> c
2.2999999999999998
>>> c = 1
>>> type(c)
<type 'float'>
>>> c
1.0
>>> c = [1,2,3]
Traceback (most recent call last):
File "<console>", line 1, in ?
File "./t.py", line 11, in __setitem__
raise TypeError, TypeError: \
illegal assignment to 'c': <type 'list'> \
cannot be coerced to <type 'float'>

0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Home