[Python-ideas] Keyword/Symbol literals

Bruce Leban bruce at leban.us
Wed Jan 21 08:36:32 CET 2015

class Symbol():
    def __getattr__(self, var):
  t = object()
  object.__setattr__(self, var, t)
  return t
    def __setattr__(self, var, val):
        raise AttributeError()

S = Symbol()

Now use S.abc and S.xyz etc. They automatically get created as unique
objects. Trying to set one of the values raises. With a little more work
you can make it pretty printable.

Is this a valuable enough feature to build into the language and dedicate a
special character to it? I think you'd have to have a lot of use cases and
a lot of usage. If it were added I think the best character to use without
colliding with anything would be !foo.

--- Bruce
Check out my new puzzle book: http://Ju.mp/ingToConclusions
Get it free here: http://Ju.mp/ingToConclusionsFree (available on iOS)

On Tue, Jan 20, 2015 at 9:20 PM, Matthew Rocklin <mrocklin at gmail.com> wrote:

> It would be nice to have literal keywords/symbols.  By this I mean, terms
> that look like words but are not previously defined variables.
> *Prior art*
> Some other languages prefix by colon, :foo,  or use a backtick,  `foo.
> julia> :foo
> :foo
> julia> typeof(:foo)
> Symbol
> user=> :foo
> :foo
> user=> (type :foo)
> clojure.lang.Keyword
> user=> `foo
> user/foo
> user=> (type `foo)
> clojure.lang.Symbol
> *Why is this useful?*
> One use case in NumPy/Pandas use is to specify columns or fields of data
> without resorting to strings.  E.g.
> df = pandas.load(...)
> df.sort(:name)
> *What do people do now?*
> Currently people use auto-generated attributes
> df.sort(df.name)
> or strings
> df.sort('name')
> auto-generated attributes work great until you want to use chained
> expressions
> df.change_dataframe().sort(some_new_column_not_in_df)
> strings work but feel unpleasant
> *Prior discussion?*
> This is a common language construct so my guess is that it has come up
> before.  Sadly Google searching the terms *keywords* and *symbols*
> results it a lot of unrelated material.  Can anyone point me to previous
> discussion?
> There are clearly issues with using :foo in that it overlaps with slice
> syntax, presumably some other character could be pressed into service if
> this was found worthwhile.
> I can come up with more motivating use cases if desired.
> Best,
> -Matthew
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150120/dc157ba6/attachment.html>

More information about the Python-ideas mailing list