[Python-ideas] Keyword/Symbol literals

Yawar Amin yawar.amin at gmail.com
Thu Jan 22 05:25:21 CET 2015


On 2015-01-21 14:38, Alexander Belopolsky wrote:
> [...]
> My use case comes from interoperability with other languages.  I
> maintain a package which provides an interface [1] between Python and
> the language [2] called Q.  Q has 3 scalar types to represent text
> data (char, byte and symbol) and the corresponding vector types.  When
> I pass Python strings to Q, I convert them to symbols because that is
> what users expect most of the time, but as a result, working with char
> vectors is unnatural.  I currently use bytes type for that, but it is
> really an abuse because bytes should map to byte vectors.

Hi, after thinking about it some more I've come to believe new, empty
classes are the best way to model symbols in Python (for now at least).
My reasoning is:

  - Symbols are tags (i.e. unique names for things).

  - In a typed language which has enums or discriminated unions (aka
    tagged unions), tags are often created from enums.

  - Enums and discriminated unions are isomorphic to base and inheriting

  - Therefore, symbols are classes which could optionally inherit from a
    base class.

In your case, you could define a function which dynamically creates
these 'symbols' for you and then stashes them somewhere for re-use.
Below, I've used the calling module's `globals()` dict, but you could
store them away very neatly in some other dict to avoid any possible
name conflicts.

    # In called module:
    class sym(object): pass
    def get_sym(sym_name, d):
      if s in d: return d[sym_name]
      new_sym = type(sym_name, (sym,), {})
      d[sym_name] = new_sym
      return new_sym
    # In calling module:
    def char_to_sym(c):
      "Map a 'character' to a symbol."
      assert len(c) == 1
      return get_sym(c, globals()) # This could be any dict.

    def str_to_syms(s): return map(char_to_sym, s)
    print str_to_syms("Hello, World!") # ==> [<class '__main__.H'>, ...]
    print char_to_sym("!") == char_to_sym("!") # ==> True



-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 834 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150121/9ce7bb91/attachment.sig>

More information about the Python-ideas mailing list