Search code examples
pythonpython-2.7enumscompatibility

How to import auto from enum in python 2.7?


I'm using an old code based in python 2.7 (Can't change this, unfortunately). I have to introduce a new feature from a piece of code based in python 3.6. This piece of code would work except because it uses the package enum, which is, as far as I know, no longer maintained. So:

from enum import Enum, auto (Doesn't work python 2.7)

Because I think "auto" was not defined in python 2.7. Is it possible to make that line working? or at least install/ import "enum.auto" or something with the same functionality?


Solution

  • You have a couple choices:

    • use aenum1 instead
    • copy/create your own auto() and stuff it into enum

    Using aenum is a two-step process:

    • pip install aenum
    • change from enum to from aenum

    Creating/copying an auto and stuffing it into enum:

    import enum
    from itertools import count
    
    def auto(it=count()):
      return next(it)
    
    enum.auto = auto
    

    1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.