lundi 23 mars 2020

How can I make enum available to users of a class without additional dependencies?

I have a number of acceptable values as an input into a class method and I think a nice way to control this is by using an enum type. The catch is that I don't want to create an additional dependencies.

Is there a nice Pythonic way to do this?

As an example, the following will work, but it won't get me code completion.

import enum

class A(enum.Enum):
  one=1
  two=2
  three=3

class Myclass:

  def method(self, a: A):
    print('Inside method')
    print(a)

  # Two approaches I've looked at
  method.input = A  # Approach 1: Associates directly with the method
  method_input = A  # Approach 2: Provides access to enum through the class

m = Myclass()

# Approach 1: Doesn't give code completion. Associates with the method
m.method(m.method.input.one)

# Approach 2: Gives code completion. Depends on a naming convention
m.method(m.method_input.one)

I've also considered putting it in the parameters, but I don't think it's appropriate since I'm only interested in a single value - though it could be done. The more promising alternative is to use a dictionary map, but that won't give my users code completion.

Aucun commentaire:

Enregistrer un commentaire