Enumerations in Python: How to Force Method Arguments

I want to use enums in python, as in the code below (java). I am in Python. I have the following Java code and want to replicate functionality in Python:

class Direction {
  public enum Direction {LEFT, RIGHT, UP, DOWN}

  public void navigate(Direction direction)
    switch(direction){
        case Direction.LEFT:
            System.out.print("left");
            break;
        case Direction.RIGHT:
            System.out.print("right");
            break;
        case Direction.UP:
            System.out.print("up");
            break;
        case Direction.DOWN:
            System.out.print("down");
            break;
  }
}

How can I get users to provide only an enumeration for a Python method?

+8
source share
3 answers

Python is dynamic and type-typed duck - variables can change type, and you cannot impose types on methods.

However, you can check the types in the body of the method using isinstance().

isinstance() isinstance() enum . -

# Python 2.x: pip install enum34
from enum import Enum

class Direction(Enum):
    LEFT = "left"
    RIGHT = "right"
    UP = "up"
    DOWN = "down"

def move(direction):

    # Type checking
    if not isinstance(direction, Direction):
        raise TypeError('direction must be an instance of Direction Enum')

    print direction.value

>>> move(Direction.LEFT)
left
>>> move("right")
TypeError: direction must be an instance of Direction Enum
+10

"" - : , , . , :

def navigate(direction):
    """Turn toward `direction` (an enum of type `Direction`)"""

    if direction == Direction.left:
         print("Left")
    elif direction == Direction.right:
         (etc., etc.)
    else:
         # Hmm, `direction` does not compare equal to any enum value:
         raise ValueError("Invalid direction "+ str(direction))
+4

alexis, :

def navigate(direction):
""":params: <string> Direction to move to"""

assert direction.lower() in ["left", "right"], "Invalid direction "
print direction

, "" "", AssertionError " ".

+1

Source: https://habr.com/ru/post/1628825/


All Articles