Skip to content

Commit

Permalink
Python: make enums extend IntEnum, fix to_i on invalid enum vals
Browse files Browse the repository at this point in the history
Fix kaitai-io/kaitai_struct#815

Note: this actually fixes the `to_i` method on enum values in Construct
as well, because `ConstructTranslator` inherits from `PythonTranslator`
and doesn't override the `enumToInt` method. The previous `enumToInt`
implementation (`s"${translate(v)}.value"`) didn't work in Construct at
all, because Construct uses its own classes for enum values (as
evidenced by our failing tests, these were `EnumInteger` and
`EnumIntegerString`, apparently defined here:
https://github.com/construct/construct/blob/3f3f30937bee74274147c6833137ad172fa62627/construct/core.py#L1865-L1883),
which don't have any `.value` attribute. But as the Construct docs say
about these classes
(https://construct.readthedocs.io/en/latest/api/mappings.html#construct.Enum):

> Returns an **integer-convertible** string (if mapping found) or an
> integer (otherwise).

... so an enum value in Construct can be always converted to an integer
using the built-in `int()` function just fine.
  • Loading branch information
generalmimon committed Oct 9, 2023
1 parent cb58862 commit bc6fb85
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -466,10 +466,10 @@ class PythonCompiler(typeProvider: ClassTypeProvider, config: RuntimeConfig)
}

override def enumDeclaration(curClass: String, enumName: String, enumColl: Seq[(Long, String)]): Unit = {
importList.add("from enum import Enum")
importList.add("from enum import IntEnum")

out.puts
out.puts(s"class ${type2class(enumName)}(Enum):")
out.puts(s"class ${type2class(enumName)}(IntEnum):")
out.inc
enumColl.foreach { case (id: Long, label: String) => out.puts(s"$label = ${translator.doIntLiteral(id)}") }
out.dec
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class PythonTranslator(provider: TypeProvider, importList: ImportList) extends B
s"int(${translate(s)}$add)"
}
override def enumToInt(v: Ast.expr, et: EnumType): String =
s"${translate(v)}.value"
s"int(${translate(v)})"
override def boolToInt(v: Ast.expr): String =
s"int(${translate(v)})"
override def floatToInt(v: Ast.expr): String =
Expand Down

0 comments on commit bc6fb85

Please sign in to comment.