Adding symbols to Python |
:: Email ::
Download area
|
Simple attempt to add symbols to Python. (Inspiration) (Disclaimer: This is an experiment, not a well-crafted module. It hasn't been tested a lot, and certainly hasn't been used in production code. But it might be a starting point for those who find this feature interesting.) Symbols are not explicitly declared or created or anything. Just use them: Also note that symbols are case insensitive. # symbols.py
class SymbolError(Exception):
pass
class Symbol:
def __init__(self, name):
self.name = name
def __repr__(self):
return "Symbol(%s)" % (self.name,)
def __cmp__(self, other):
if isinstance(other, Symbol):
return cmp(self.name, other.name)
else:
return -1
class SymbolManager:
def __init__(self):
self.__dict__['symbols'] = {} # avoid __setattr__
def __getattr__(self, name):
name = name.lower() # symbols are case insensitive
try:
return self.symbols[name]
except KeyError:
s = Symbol(name)
self.symbols[name] = s
return s
def __setattr__(self, name, value):
raise SymbolError, "Adding symbols manually is not allowed"
def __delattr__(self, name):
raise SymbolError, "Deleting symbols is not allowed"
# register symbol manager
import __builtin__
__builtin__.symbols = SymbolManager()
# test test...
a = ("foobar", symbols.open)
if a[1] == symbols.open:
print "oh, ya!"
if a[1] == symbols.close:
print "oh noes!"
# comparing symbols is possible, though maybe not very useful:
print symbols.this > symbols.that
print symbols.a > symbols.b
print symbols.q > symbols.c
print symbols.ABC == symbols.abc # they're the same
print symbols.fred
(Last update: 2005-11-23 13:38) |