Skip to main content

escape_name

Function escape_name 

Source
pub fn escape_name(name: &str) -> String
Expand description

The name an IDL identifier takes in Python.

A trailing underscore where the identifier would otherwise bind over something the generated file itself relies on. PEP 8 gives that rule for the keyword case — class_, lambda_ — and the same escape covers the other two cases, because in Python they are the same problem:

  • a keyword, which does not parse as a name at all;
  • a soft keyword (match, case, type), which parses but reads as a statement to anyone scanning the file;
  • a name the generated module binds — dataclasses, typing, int, list — which would be shadowed. This is not hypothetical and it is not caught by the parser: an @optional member called int becomes a class attribute set to None, and typing.get_type_hints resolves annotations against the class namespace first, so every int in that class would then resolve to None;
  • mro, which enum.EnumType refuses as a member name. It is the only such name — name, value, property and auto are all accepted, measured against CPython 3.14 — and an enumeration carrying it raises ValueError when the module is imported.

The IDL name is not lost when this fires: the materialiser writes it into the field’s dataclasses.field(metadata=...) and into a comment above every other kind of declaration.

A leading underscore is left alone. It is a legal Python identifier and renaming it would make the generated name differ from the IDL for no reason.