Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums in Python: How to enforce in method arguments

I want to use enums in python like in code below (java). I am a greenhorn in Python. I have the following code in Java and want to replicate the 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 enforce users to only provide an enum to a Python method?

like image 982
user2678074 Avatar asked Feb 15 '16 10:02

user2678074


People also ask

How do you pass an enum in a method argument?

Change the signature of the CreateFile method to expect a SupportedPermissions value instead of plain Enum. Show activity on this post. Show activity on this post. First change the method parameter Enum supportedPermissions to SupportedPermissions supportedPermissions .

Can enums have methods Python?

Customize Python enum classes Python enumerations are classes. It means that you can add methods to them, or implement the dunder methods to customize their behaviors.

Can you declare enum in method?

Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.


1 Answers

Python is dynamic and duck typed - variables can change type and you can't force types on methods.

You can, however, check for types in the body of a method using isinstance().

isinstance() will allow users to subclass your enum for future extensibility. - See comments

E.g.

# 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
like image 143
Alastair McCormack Avatar answered Sep 19 '22 03:09

Alastair McCormack