Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to document and use enum-like data types in Python?

Let's assume that the current code is using strings for parameters and you want to document their valid values.

Example

def MyFunc(region = None):
    if region in ['A','B','C', None]:
        # dosomething
    else:
        # complain about invalid parameter

Now the question is how can I improve this design in order to solve two problems:

  • be able to use the auto-complete functionality in IDEs to auto-complete with possible values for the parameter.

  • document the list of valid values for the parameter (currently the code is documented using doxygen)

like image 349
sorin Avatar asked Sep 23 '11 09:09

sorin


2 Answers

Here is a similar question: How can I represent an 'Enum' in Python?

It suggests implementing something like:

class MyClass :
    A = 0   """The Letter A"""
    B = 1   """The Letter B"""
    C = 2   """The Letter C"""
    D = 3   """The Letter D"""

variable = MyClass.A    # Ok
variable = MyClass.E    # Error

With this you get your IDE auto-complete as well. (Which contrary to S.Lott's opinion, I use all the time... old java habit I guess).

It's considered poor style to use a docstring to restate the obvious, and I think in this case makes the code readability worse. For more information on docstrings:

http://www.python.org/dev/peps/pep-0257/

If you're curious why there is no enum type in Python, you might check out the PEP:

http://www.python.org/dev/peps/pep-0354/

like image 143
Adam Morris Avatar answered Oct 15 '22 09:10

Adam Morris


Enums are supported as of 3.4: https://docs.python.org/3.4/library/enum.html

like image 31
gerardw Avatar answered Oct 15 '22 11:10

gerardw