Here’s the SymbolType package that adds symbols to Python. Can those who have done anything useful with Lisp/Scheme tell me what how can I take advantage of this type in Python?
Can it be used to isolate strings coming from outside (from the web) from internal code?
$ sudo easy_install SymbolType
$ ipython
Unfortunately, you can’t use symbols to pass values as kwargs:
In [7]: X = s('X', __name__)
In [9]: a = {X: 10}
In [12]: Y = s('Y', __name__)
In [13]: a.update({Y: 20})
In [14]: a
Out[14]: {X: 10, Y: 20}
In [15]: for (k, v) in a.items():
....: print k, v
Y 20
X 10
In [16]: def z(X=0,Y=1):
....: print X, Y
....:
In [17]: z(**a)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
...<ipython console> in <module>()
TypeError: z() keywords must be strings
Symbols are not a replacement for strings. While both are represented by a
sequence of characters, a symbol shouldn’t be used in place of a string when
this is the dominant property. Symbols represent a unique identity.
This means that pointer equality
(instead of content equality) can be used to compare them.
For this reason, symbols are often used as constants, enumeration elements, hash table keys
or identifiers (in lisp).
In Lisp, the first time you reference a symbol, a corresponding entry in the
symbol table is created. If the same symbol is referenced thereafter,
it will be looked up and represent the same value.
I’m not a Python programmer, but since symbols are not built into
the Python language, their use may be limited or not very convenient.
You shouldn’t use them for isolating strings. Use a wrapper class for that.
Edit: reading through the SymbolType docs, i saw that they bundle the originating
namespace (through
__name__). Common Lisp does that, too. One might be able to use thisfacility in some fashion.
Also read this question.