SnakeBridge.Generator.TypeMapper (SnakeBridge v0.9.0)

View Source

Maps Python type annotations to Elixir typespec AST.

This module converts Python type dictionaries (as produced by the introspection script) into Elixir typespec AST using quote. The AST can then be used to generate @spec declarations in generated modules.

Type Mappings

Python TypeElixir Type
intinteger()
floatfloat()
strString.t()
boolboolean()
bytesbinary()
Nonenil
list[T]list(T)
dict[K, V]map(K, V)
tuple[T1, T2, ...]{T1, T2, ...}
set[T]MapSet.t(T)
Optional[T]T | nil
Union[T1, T2, ...]T1 | T2 | ...
ClassNameClassName.t()
Anyany()

Examples

iex> TypeMapper.to_spec(%{"type" => "int"})
{:integer, [], []}

iex> TypeMapper.to_spec(%{"type" => "list", "element_type" => %{"type" => "str"}})
{{:., [], [{:__aliases__, [alias: false], [:String]}, :t]}, [], []}
|> Macro.to_string()
"list(String.t())"

Summary

Types

context()

@type context() :: %{
  class_map: %{required({String.t(), String.t()}) => String.t()},
  name_index: %{required(String.t()) => MapSet.t(String.t())}
}

Functions

build_context(classes)

@spec build_context([map()]) :: context()

to_spec(python_type)

@spec to_spec(map() | nil) :: Macro.t()

Converts a Python type dictionary to an Elixir typespec AST.

Parameters

  • python_type - A map representing a Python type annotation

Returns

An AST node (quoted expression) representing the equivalent Elixir typespec. Class types resolve to generated modules only when a context is provided (via to_spec/2 or with_context/2), otherwise they default to term().

Examples

iex> python_type = %{"type" => "int"}
iex> ast = SnakeBridge.Generator.TypeMapper.to_spec(python_type)
iex> Macro.to_string(ast)
"integer()"

iex> python_type = %{"type" => "list", "element_type" => %{"type" => "int"}}
iex> ast = SnakeBridge.Generator.TypeMapper.to_spec(python_type)
iex> Macro.to_string(ast)
"list(integer())"

to_spec(python_type, context)

@spec to_spec(map() | nil, context()) :: Macro.t()

with_context(context, fun)

@spec with_context(context(), (-> result)) :: result when result: var