0

Consider the following MWE:

from enum import Enum

class IMeasurements(Enum):
  pass

class _MYMeasurements(IMeasurements):
    FIRST = 0
    SECOND = 1

class MYParser():
    def __init__(self):
        pass

    @staticmethod
    def get_measurement_enum():
        return _MYMeasurements

parser = MYParser()

weld_measurements_enum: IMeasurements = parser.get_measurement_enum()

n_measures = len(weld_measurements_enum)

print(n_measures)

The project I am working on uses abstraction on several levels, to keep things modular and force implementations to adhere to some interfaces. Notably, the Enum IMeasurements doesn't have members as-is, but it's extension _MyMeasurements does.

Now this code works, Python returns the expected value. But when checking this code for typing errors with mypy, I get the error message:

Argument 1 to "len" has incompatible type "IMeasurements"; expected "Sized"

One of my attempted solutions was to use EnumMeta in place of Enum for IMeasurements, but while this silents mypy, it leads to another error: TypeError: object of type 'type' has no len().

Is this a bug in mypy? If not, how am I supposed to proceed in those cases?

Thanks!

beeb
  • 1,187
  • 11
  • 32
  • 1
    Since `weld_measurements_enum` is a variable that holds enums (i.e. classes), you have to annotate it with [`typing.Type`](https://docs.python.org/3/library/typing.html#typing.Type). – Aran-Fey Sep 06 '18 at 15:07
  • @Aran-Fey have you tried? the result is the same for me: `Argument 1 to "len" has incompatible type "Type[Any]"; expected "Sized"`. I suggest you remove the "duplicate" marking – beeb Sep 06 '18 at 15:10
  • Just found that using Type[Enum] seems to be working. Could you post your answer as an answer and re-open my question? It's not really easy to make the link to the "duplicate" you posted. – beeb Sep 06 '18 at 15:15
  • Well, that's why I left a comment explaining the link between the two questions. I think that's good enough. I don't want to write an answer, but I wouldn't horribly mind reopening the question if someone else is going to post one. – Aran-Fey Sep 06 '18 at 15:18
  • As you wish, I think the key part of the answer is you need to use `Type[Enum]` to get mypy to understand it is an iterable/sized. Thanks for your help – beeb Sep 06 '18 at 15:19

0 Answers0