5

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)

Michael J. Barber
  • 24,518
  • 9
  • 68
  • 88
sorin
  • 161,544
  • 178
  • 535
  • 806
  • 1
    IDE auto-complete is a waste of time. There, I said it. More importantly, please explain why region is a string. There are a lot of choices for enumerating values like this. Why did you choose a string? – S.Lott Sep 23 '11 at 09:56

2 Answers2

4

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/

Community
  • 1
  • 1
Adam Morris
  • 8,265
  • 12
  • 45
  • 68
2

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

gerardw
  • 5,822
  • 46
  • 39