Skip to content

Latest commit

 

History

History
143 lines (97 loc) · 3.63 KB

File metadata and controls

143 lines (97 loc) · 3.63 KB
title Enumerations
description How prik handles Fortran `enum` and enumerators
audience users
prerequisites wrapping modules, data types
related wrapping-modules.md, generic-interfaces.md
status maintained
publication reviewed

Enumerations

prik turns supported Fortran enum declarations into typed integer constants. It does not generate Python Enum or IntEnum classes — values remain plain integers with the resolved dtype.


Complete Example

The source, generated contract, and Python call describe the same module. The result stays visible below the three views.

Fortran source Generated contract Python usage

Fortran source

Create colors.f90:

module colors_api
  implicit none

  enum, bind(C)
    enumerator :: red = -1
    enumerator :: blue
    enumerator :: green = 10
    enumerator :: yellow
  end enum

contains

  integer(4) function round_trip_color(value) result(output)
    integer(4), intent(in) :: value
    output = value
  end function round_trip_color

end module colors_api

Build it:

python3 -m prik colors.f90 --out-dir build/colors

Generated Contract

The generated colors_api.pyi is:

from prik.contracts import Addr, Arg, Final, Int32, native_call

red: Final[Int32] = -1

blue: Final[Int32] = 0

green: Final[Int32] = 10

yellow: Final[Int32] = 11

@native_call([Addr(Arg(0))])
def round_trip_color(
    value: Int32
) -> Int32: ...

Generate it:

python3 -m prik generate --pyi colors.f90

Usage in Python

import sys

sys.path.insert(0, "build/colors")
from colors.colors_api import blue, green, red, round_trip_color, yellow

print(red, blue, green, yellow)  # -1 0 10 11

# Pass enumerator values to procedures
result = round_trip_color(green)
print(result)                    # 10

Result:

-1 0 10 11
10

Key Points

  • Enumerators become module constants declared with Final[...] in the generated semantic .pyi; the native enumerator value cannot change.
  • They use the resolved integer dtype (usually Int32).
  • Rebinding an imported name in Python only creates a local shadow — it does not change the native value.
  • No automatic runtime validation — passing any integer of the correct dtype works.
  • Static type checkers see them as integer constants.

Limitations

  • No native Enum class is generated in Python.
  • If you want a proper Python Enum, define one in your application code and pass .value (as np.int32).

Next