2

I use enumerations in Python 2.7 with enum34, which backports the enumerations of Python 3.4 to 2.7.

In my script I have functions which get some entry of an enumeration. Since this may become a multi-author project, I want to declare methods explicitly type safe:

def someFunction(some_enum_item):
    """
    :param some_enum_item: one entry out of my Enum SAMPLE_ENUM
    :type some_enum_item: SAMPLE_ENUM
    """
    if isinstance(some_enum_item, SAMPLE_ENUM):
        ...
    else:
        ...

So, I want to test against the parameter if it is really an instance of SAMPLE_ENUM and additionally I want to have an IDE recognizing that the function only takes entries of a specific Enum.

Is isinstance the right way to test if the parameter has the correct type?

How am I modelling the :type some_enum_item: correctly? At the moment :type some_enum_item: SAMPLE_ENUM just checks if the parameter is the class SAMPLE_ENUM rather than an item of this enumeration (hence, the IDE complains when I'm passing an entry of the enumeration to the function).

daniel451
  • 10,626
  • 19
  • 67
  • 125
  • You should tag this with your IDE as the question pertains directly to it. Python doesn't care what you have in your docstrings. – Ethan Furman Feb 14 '16 at 18:37

1 Answers1

1

I can't answer the IDE portion of your question, but as far is the isinstance check -- yes, that is a correct way (and the most obvious way) to determine if the object you received is a member of the enumeration.

Another way, less obvious way, is:

if some_enum_item in SAMPLE_ENUM:
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
  • Is this a good/pythonic way (`isinstance`) to check parameter types before executing the actual function? – daniel451 Feb 15 '16 at 00:41
  • 1
    @ascenator: Yes, `isinstance` is the pythonic way to check things. Whether you *should* is a different question. :) – Ethan Furman Feb 15 '16 at 00:46
  • What do you exactly mean with whether I *should*? Is it a bad design thing? How do you check the types of function parameters? – daniel451 Feb 15 '16 at 00:48