mirror of
https://github.com/google/flatbuffers.git
synced 2026-06-02 12:05:50 +00:00
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")
```
109 lines
3.1 KiB
Python
109 lines
3.1 KiB
Python
# automatically generated by the FlatBuffers compiler, do not modify
|
|
|
|
# namespace: Example
|
|
|
|
import flatbuffers
|
|
from flatbuffers.compat import import_numpy
|
|
from typing import Any
|
|
from MyGame.Example.ArrayStruct import ArrayStruct
|
|
from typing import Optional
|
|
np = import_numpy()
|
|
|
|
class ArrayTable(object):
|
|
__slots__ = ['_tab']
|
|
|
|
@classmethod
|
|
def GetRootAs(cls, buf, offset: int = 0):
|
|
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset)
|
|
x = ArrayTable()
|
|
x.Init(buf, n + offset)
|
|
return x
|
|
|
|
@classmethod
|
|
def GetRootAsArrayTable(cls, buf, offset=0):
|
|
"""This method is deprecated. Please switch to GetRootAs."""
|
|
return cls.GetRootAs(buf, offset)
|
|
@classmethod
|
|
def ArrayTableBufferHasIdentifier(cls, buf, offset, size_prefixed=False):
|
|
return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x41\x52\x52\x54", size_prefixed=size_prefixed)
|
|
|
|
# ArrayTable
|
|
def Init(self, buf: bytes, pos: int):
|
|
self._tab = flatbuffers.table.Table(buf, pos)
|
|
|
|
# ArrayTable
|
|
def A(self) -> Optional[ArrayStruct]:
|
|
o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4))
|
|
if o != 0:
|
|
x = o + self._tab.Pos
|
|
obj = ArrayStruct()
|
|
obj.Init(self._tab.Bytes, x)
|
|
return obj
|
|
return None
|
|
|
|
def ArrayTableStart(builder: flatbuffers.Builder):
|
|
builder.StartObject(1)
|
|
|
|
def Start(builder: flatbuffers.Builder):
|
|
ArrayTableStart(builder)
|
|
|
|
def ArrayTableAddA(builder: flatbuffers.Builder, a: Any):
|
|
builder.PrependStructSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(a), 0)
|
|
|
|
def AddA(builder: flatbuffers.Builder, a: Any):
|
|
ArrayTableAddA(builder, a)
|
|
|
|
def ArrayTableEnd(builder: flatbuffers.Builder) -> int:
|
|
return builder.EndObject()
|
|
|
|
def End(builder: flatbuffers.Builder) -> int:
|
|
return ArrayTableEnd(builder)
|
|
|
|
import MyGame.Example.ArrayStruct
|
|
try:
|
|
from typing import Optional
|
|
except:
|
|
pass
|
|
|
|
class ArrayTableT(object):
|
|
|
|
# ArrayTableT
|
|
def __init__(
|
|
self,
|
|
a = None,
|
|
):
|
|
self.a = a # type: Optional[MyGame.Example.ArrayStruct.ArrayStructT]
|
|
|
|
@classmethod
|
|
def InitFromBuf(cls, buf, pos):
|
|
arrayTable = ArrayTable()
|
|
arrayTable.Init(buf, pos)
|
|
return cls.InitFromObj(arrayTable)
|
|
|
|
@classmethod
|
|
def InitFromPackedBuf(cls, buf, pos=0):
|
|
n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos)
|
|
return cls.InitFromBuf(buf, pos+n)
|
|
|
|
@classmethod
|
|
def InitFromObj(cls, arrayTable):
|
|
x = ArrayTableT()
|
|
x._UnPack(arrayTable)
|
|
return x
|
|
|
|
# ArrayTableT
|
|
def _UnPack(self, arrayTable):
|
|
if arrayTable is None:
|
|
return
|
|
if arrayTable.A() is not None:
|
|
self.a = MyGame.Example.ArrayStruct.ArrayStructT.InitFromObj(arrayTable.A())
|
|
|
|
# ArrayTableT
|
|
def Pack(self, builder):
|
|
ArrayTableStart(builder)
|
|
if self.a is not None:
|
|
a = self.a.Pack(builder)
|
|
ArrayTableAddA(builder, a)
|
|
arrayTable = ArrayTableEnd(builder)
|
|
return arrayTable
|