Enums: making a single enum

Chris Angelico rosuav at gmail.com
Sat May 26 09:54:51 EDT 2018


On Sat, May 26, 2018 at 6:50 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sat, 26 May 2018 18:14:08 +1000, Chris Angelico wrote:
>
>> On Sat, May 26, 2018 at 6:00 PM, Steven D'Aprano
>> <steve+comp.lang.python at pearwood.info> wrote:
>>> Actually I don't really need all the features of Enums, I might just
>>> define my own class:
>>>
>>>
>>> class Maybe:
>>>      def __repr__(self):
>>>          return "Maybe"
>>>
>>> Maybe = Maybe()
>>>
>>>
>>>
>>> I wish there was a simpler way to define symbols with identity but no
>>> state or behaviour...
>>
>> You DO have behaviour though - the repr is a behaviour of that object.
>> So what you have there (reusing the name for the instance) seems decent
>> to me.
>
> I *just knew* some clever Dick (or clever Chris in this case...) would
> point out that repr is behaviour. Technically you are correct (the best
> kind of correct...) but in a practical sense we don't really count having
> a repr as behaviour. All objects ought to have a repr: calling print(obj)
> or displaying the object in the REPL shouldn't raise an exception. Even
> None has a repr :-)

Sure, but the default repr is one behaviour, and a customized repr is
different behaviour. You do get a repr even without creating a class,
but you don't want that one, you want something more custom.

> I want an easy way to make new objects like None and NotImplemented
> without having to explicitly define a class first. Some languages make
> that real easy (although the semantics might not be quite identical):
>
>     Ruby                :Maybe
>     Javascript          Symbol("Maybe")
>     Julia               :Maybe or Symbol("Maybe")
>     Scala               'Maybe
>     Elixir              :Maybe
>     Erland              maybe or 'Maybe'
>
>
> Elixir and Erland call them atoms; Erland also requires them to begin
> with a lowercase letter, otherwise they must be surrounded by single
> quotes.
>
>
> Hey-Chris-you-want-to-collaborate-on-a-PEP-for-this-ly y'rs,

Sure. Basically it'd be a builtin that, whenever instantiated, returns
a new object (guaranteed to be unique) identified by the given string.
Pretty simple and straight-forward. In fact, I wouldn't even start a
PEP yet. Toss it out onto -ideas and see who's interested!

class Symbol: # or Atom:
    __slots__ = ("label",)
    def __init__(self, label):
        self.label = label
    def __repr__(self):
        return f"Symbol({self.label!r})"

Seems pretty non-controversial, which means it's almost guaranteed to
reach 100+ posts debating what the name should be.

ChrisA



More information about the Python-list mailing list