[Python] Enhance object API __init__ with typed keyword arguments (#8615)

This commit significantly improves the developer experience for the Python Object-Based API by overhauling the generated `__init__` method for `T`-suffixed classes.

Previously, `T` objects had to be instantiated with an empty constructor, and their fields had to be populated manually one by one. This was verbose and not idiomatic Python.

This change modifies the Python code generator (`GenInitialize`) to produce `__init__` methods that are:

1.  **Keyword-Argument-Friendly**: The constructor now accepts all table/struct fields as keyword arguments, allowing for concise, single-line object creation.

2.  **Fully Typed**: The signature of the `__init__` method is now annotated with Python type hints. This provides immediate benefits for static analysis tools (like Mypy) and IDEs, enabling better autocompletion and type checking.

3.  **Correctly Optional**: The generator now correctly wraps types in `Optional[...]` if their default value is `None`. This applies to strings, vectors, and other nullable fields, ensuring strict type safety.

The new approach remains **fully backward-compatible**, as all arguments have default values. Existing code that uses the empty constructor will continue to work without modification.

#### Example of a Generated `__init__`

**Before:**

```python
class KeyValueT(object):
    def __init__(self):
        self.key = None  # type: str
        self.value = None  # type: str
```

**After:**

```python
class KeyValueT(object):
    def __init__(self, key: Optional[str] = None, value: Optional[str] = None):
        self.key = key
        self.value = value
```

#### Example of User Code

**Before:**

```python
# Old, verbose way
kv = KeyValueT()
kv.key = "instrument"
kv.value = "EUR/USD"
```

**After:**

```python
# New, Pythonic way
kv = KeyValueT(key="instrument", value="EUR/USD")
```
This commit is contained in:
Łukasz Kurowski
2025-07-23 08:57:39 +02:00
committed by GitHub
parent ca73ff34b7
commit c526cb640b
31 changed files with 745 additions and 293 deletions

View File

@@ -287,6 +287,63 @@ class PythonStubGenerator {
}
}
void GenerateObjectInitializerStub(std::stringstream &stub,
const StructDef *struct_def,
Imports *imports) const {
stub << " def __init__(\n";
stub << " self,\n";
for (const FieldDef *field : struct_def->fields.vec) {
if (field->deprecated) continue;
std::string field_name = namer_.Field(*field);
std::string field_type;
const Type &type = field->value.type;
if (IsScalar(type.base_type)) {
field_type = TypeOf(type, imports);
if (field->IsOptional()) { field_type += " | None"; }
} else {
switch (type.base_type) {
case BASE_TYPE_STRUCT: {
Import import_ =
imports->Import(ModuleFor(type.struct_def),
namer_.ObjectType(*type.struct_def));
field_type = "'" + import_.name + "' | None";
break;
}
case BASE_TYPE_STRING:
field_type = "str | None";
break;
case BASE_TYPE_ARRAY:
case BASE_TYPE_VECTOR: {
imports->Import("typing");
if (type.element == BASE_TYPE_STRUCT) {
Import import_ =
imports->Import(ModuleFor(type.struct_def),
namer_.ObjectType(*type.struct_def));
field_type = "typing.List['" + import_.name + "'] | None";
} else if (type.element == BASE_TYPE_STRING) {
field_type = "typing.List[str] | None";
} else {
field_type = "typing.List[" + TypeOf(type.VectorType(), imports) +
"] | None";
}
break;
}
case BASE_TYPE_UNION:
field_type = UnionObjectType(*type.enum_def, imports);
break;
default:
field_type = "typing.Any";
break;
}
}
stub << " " << field_name << ": " << field_type << " = ...,\n";
}
stub << " ) -> None: ...\n";
}
void GenerateObjectStub(std::stringstream &stub, const StructDef *struct_def,
Imports *imports) const {
std::string name = namer_.ObjectType(*struct_def);
@@ -300,6 +357,8 @@ class PythonStubGenerator {
stub << " " << GenerateObjectFieldStub(field, imports) << "\n";
}
GenerateObjectInitializerStub(stub, struct_def, imports);
stub << " @classmethod\n";
stub << " def InitFromBuf(cls, buf: bytes, pos: int) -> " << name
<< ": ...\n";
@@ -1694,6 +1753,7 @@ class PythonGenerator : public BaseGenerator {
field_type = package_reference + "." + field_type;
import_list->insert("import " + package_reference);
}
field_type = "'" + field_type + "'";
break;
case BASE_TYPE_STRING: field_type += "str"; break;
case BASE_TYPE_NONE: field_type += "None"; break;
@@ -1755,8 +1815,12 @@ class PythonGenerator : public BaseGenerator {
void GenInitialize(const StructDef &struct_def, std::string *code_ptr,
std::set<std::string> *import_list) const {
std::string code;
std::string signature_params;
std::string init_body;
std::set<std::string> import_typing_list;
signature_params += GenIndents(2) + "self,";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
auto &field = **it;
@@ -1783,6 +1847,7 @@ class PythonGenerator : public BaseGenerator {
// Scalar or sting fields.
field_type = GetBasePythonTypeForScalarAndString(base_type);
if (field.IsScalarOptional()) {
import_typing_list.insert("Optional");
field_type = "Optional[" + field_type + "]";
}
break;
@@ -1791,18 +1856,23 @@ class PythonGenerator : public BaseGenerator {
const auto default_value = GetDefaultValue(field);
// Writes the init statement.
const auto field_field = namer_.Field(field);
code += GenIndents(2) + "self." + field_field + " = " + default_value +
" # type: " + field_type;
// Build signature with keyword arguments, type hints, and default values.
signature_params += GenIndents(2) + field_field + " = " + default_value + ",";
// Build the body of the __init__ method.
init_body += GenIndents(2) + "self." + field_field + " = " + field_field +
" # type: " + field_type;
}
// Writes __init__ method.
auto &code_base = *code_ptr;
GenReceiverForObjectAPI(struct_def, code_ptr);
code_base += "__init__(self):";
if (code.empty()) {
code_base += "__init__(" + signature_params + GenIndents(1) + "):";
if (init_body.empty()) {
code_base += GenIndents(2) + "pass";
} else {
code_base += code;
code_base += init_body;
}
code_base += "\n";